Skip to content

Commit 2001900

Browse files
Licht-Tserhiy-storchaka
authored andcommitted
bpo-32255: Always quote a single empty field when write into a CSV file. (#4769)
This allows to distinguish an empty row from a row consisting of a single empty field.
1 parent e0720cd commit 2001900

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

Lib/test/test_csv.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,29 @@ def write(self, buf):
207207
with TemporaryFile("w+", newline='') as fileobj:
208208
writer = csv.writer(fileobj)
209209
self.assertRaises(TypeError, writer.writerows, None)
210-
writer.writerows([['a','b'],['c','d']])
210+
writer.writerows([['a', 'b'], ['c', 'd']])
211211
fileobj.seek(0)
212212
self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n")
213213

214+
def test_writerows_with_none(self):
215+
with TemporaryFile("w+", newline='') as fileobj:
216+
writer = csv.writer(fileobj)
217+
writer.writerows([['a', None], [None, 'd']])
218+
fileobj.seek(0)
219+
self.assertEqual(fileobj.read(), "a,\r\n,d\r\n")
220+
221+
with TemporaryFile("w+", newline='') as fileobj:
222+
writer = csv.writer(fileobj)
223+
writer.writerows([[None], ['a']])
224+
fileobj.seek(0)
225+
self.assertEqual(fileobj.read(), '""\r\na\r\n')
226+
227+
with TemporaryFile("w+", newline='') as fileobj:
228+
writer = csv.writer(fileobj)
229+
writer.writerows([['a'], [None]])
230+
fileobj.seek(0)
231+
self.assertEqual(fileobj.read(), 'a\r\n""\r\n')
232+
214233
@support.cpython_only
215234
def test_writerows_legacy_strings(self):
216235
import _testcapi

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1554,6 +1554,7 @@ Joel Taddei
15541554
Arfrever Frehtes Taifersar Arahesis
15551555
Hideaki Takahashi
15561556
Takase Arihiro
1557+
Licht Takeuchi
15571558
Indra Talip
15581559
Neil Tallim
15591560
Geoff Talvola
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
A single empty field is now always quoted when written into a CSV file.
2+
This allows to distinguish an empty row from a row consisting of a single empty field.
3+
Patch by Licht Takeuchi.

Modules/_csv.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1238,7 +1238,7 @@ csv_writerow(WriterObj *self, PyObject *seq)
12381238
if (PyErr_Occurred())
12391239
return NULL;
12401240

1241-
if (self->num_fields > 0 && self->rec_size == 0) {
1241+
if (self->num_fields > 0 && self->rec_len == 0) {
12421242
if (dialect->quoting == QUOTE_NONE) {
12431243
PyErr_Format(_csvstate_global->error_obj,
12441244
"single empty field record must be quoted");

0 commit comments

Comments
 (0)