]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-12178: Fix escaping of escapechar in csv.writer() (GH-13710)
authorBerker Peksag <berker.peksag@gmail.com>
Sun, 20 Sep 2020 06:38:07 +0000 (09:38 +0300)
committerGitHub <noreply@github.com>
Sun, 20 Sep 2020 06:38:07 +0000 (09:38 +0300)
Co-authored-by: Itay Elbirt <anotahacou@gmail.com>
Lib/test/test_csv.py
Misc/NEWS.d/next/Library/2019-05-31-23-54-28.bpo-12178.N6FLCZ.rst [new file with mode: 0644]
Modules/_csv.c

index 38160220853ea836f3436649700f2e35c6464fa7..a98707ce3caed77c3d2fb144a614febe27eb8d4c 100644 (file)
@@ -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 (file)
index 0000000..80e2a7b
--- /dev/null
@@ -0,0 +1,3 @@
+:func:`csv.writer` now correctly escapes *escapechar* when input
+contains *escapechar*.  Patch by Catalin Iacob, Berker Peksag,
+and Itay Elbirt.
index da61db9377f94d17950f769b83e0c2dea4bd1e60..594f6c14727262773e65e42c5e1181e014287edd 100644 (file)
@@ -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;
             }