From: Berker Peksag Date: Sun, 20 Sep 2020 06:38:07 +0000 (+0300) Subject: bpo-12178: Fix escaping of escapechar in csv.writer() (GH-13710) X-Git-Tag: v3.10.0a1~86 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=5c0eed7375fdd791cc5e19ceabfab4170ad44062;p=thirdparty%2FPython%2Fcpython.git bpo-12178: Fix escaping of escapechar in csv.writer() (GH-13710) Co-authored-by: Itay Elbirt --- diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py index 38160220853e..a98707ce3cae 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -202,6 +202,20 @@ class Test_Csv(unittest.TestCase): escapechar='\\', quoting = csv.QUOTE_NONE) self._write_test(['a',1,'p,q'], 'a,1,p\\,q', escapechar='\\', quoting = csv.QUOTE_NONE) + self._write_test(['\\', 'a'], '\\\\,a', + escapechar='\\', quoting=csv.QUOTE_NONE) + self._write_test(['\\', 'a'], '\\\\,a', + escapechar='\\', quoting=csv.QUOTE_MINIMAL) + self._write_test(['\\', 'a'], '"\\\\","a"', + escapechar='\\', quoting=csv.QUOTE_ALL) + self._write_test(['\\ ', 'a'], '\\\\ ,a', + escapechar='\\', quoting=csv.QUOTE_MINIMAL) + self._write_test(['\\,', 'a'], '\\\\\\,,a', + escapechar='\\', quoting=csv.QUOTE_NONE) + self._write_test([',\\', 'a'], '",\\\\",a', + escapechar='\\', quoting=csv.QUOTE_MINIMAL) + self._write_test(['C\\', '6', '7', 'X"'], 'C\\\\,6,7,"X"""', + escapechar='\\', quoting=csv.QUOTE_MINIMAL) def test_write_iterable(self): self._write_test(iter(['a', 1, 'p,q']), 'a,1,"p,q"') diff --git a/Misc/NEWS.d/next/Library/2019-05-31-23-54-28.bpo-12178.N6FLCZ.rst b/Misc/NEWS.d/next/Library/2019-05-31-23-54-28.bpo-12178.N6FLCZ.rst new file mode 100644 index 000000000000..80e2a7b5fbb2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-05-31-23-54-28.bpo-12178.N6FLCZ.rst @@ -0,0 +1,3 @@ +:func:`csv.writer` now correctly escapes *escapechar* when input +contains *escapechar*. Patch by Catalin Iacob, Berker Peksag, +and Itay Elbirt. diff --git a/Modules/_csv.c b/Modules/_csv.c index da61db9377f9..594f6c147272 100644 --- a/Modules/_csv.c +++ b/Modules/_csv.c @@ -1040,6 +1040,9 @@ join_append_data(WriterObj *self, unsigned int field_kind, const void *field_dat else want_escape = 1; } + else if (c == dialect->escapechar) { + want_escape = 1; + } if (!want_escape) *quoted = 1; }