Skip to content

Commit ce5a3cd

Browse files
miss-islingtonserhiy-storchaka
authored andcommitted
bpo-32255: Always quote a single empty field when write into a CSV file. (GH-4769) (#4810)
This allows to distinguish an empty row from a row consisting of a single empty field. (cherry picked from commit 2001900)
1 parent 82adaf5 commit ce5a3cd

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
@@ -1525,6 +1525,7 @@ Joel Taddei
15251525
Arfrever Frehtes Taifersar Arahesis
15261526
Hideaki Takahashi
15271527
Takase Arihiro
1528+
Licht Takeuchi
15281529
Indra Talip
15291530
Neil Tallim
15301531
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
@@ -1245,7 +1245,7 @@ csv_writerow(WriterObj *self, PyObject *seq)
12451245
if (PyErr_Occurred())
12461246
return NULL;
12471247

1248-
if (self->num_fields > 0 && self->rec_size == 0) {
1248+
if (self->num_fields > 0 && self->rec_len == 0) {
12491249
if (dialect->quoting == QUOTE_NONE) {
12501250
PyErr_Format(_csvstate_global->error_obj,
12511251
"single empty field record must be quoted");

0 commit comments

Comments
 (0)