Skip to content
Permalink
Browse files

bpo-32255: Always quote a single empty field when write into a CSV fi…

…le. (GH-4769) (#4810)

This allows to distinguish an empty row from a row consisting of a single empty field.
(cherry picked from commit 2001900)
  • Loading branch information...
miss-islington authored and serhiy-storchaka committed Dec 12, 2017
1 parent 82adaf5 commit ce5a3cd9b15c9379753aefabd696bff11495cbbb
Showing with 25 additions and 2 deletions.
  1. +20 −1 Lib/test/test_csv.py
  2. +1 −0 Misc/ACKS
  3. +3 −0 Misc/NEWS.d/next/Library/2017-12-12-07-29-06.bpo-32255.2bfNmM.rst
  4. +1 −1 Modules/_csv.c
@@ -207,10 +207,29 @@ def write(self, buf):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
self.assertRaises(TypeError, writer.writerows, None)
writer.writerows([['a','b'],['c','d']])
writer.writerows([['a', 'b'], ['c', 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n")

def test_writerows_with_none(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a', None], [None, 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,\r\n,d\r\n")

with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([[None], ['a']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), '""\r\na\r\n')

with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a'], [None]])
fileobj.seek(0)
self.assertEqual(fileobj.read(), 'a\r\n""\r\n')

@support.cpython_only
def test_writerows_legacy_strings(self):
import _testcapi
@@ -1525,6 +1525,7 @@ Joel Taddei
Arfrever Frehtes Taifersar Arahesis
Hideaki Takahashi
Takase Arihiro
Licht Takeuchi
Indra Talip
Neil Tallim
Geoff Talvola
@@ -0,0 +1,3 @@
A single empty field is now always quoted when written into a CSV file.
This allows to distinguish an empty row from a row consisting of a single empty field.
Patch by Licht Takeuchi.
@@ -1245,7 +1245,7 @@ csv_writerow(WriterObj *self, PyObject *seq)
if (PyErr_Occurred())
return NULL;

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

0 comments on commit ce5a3cd

Please sign in to comment.
You can’t perform that action at this time.