bpo-12178: Fix escaping of escapechar in csv.writer() (GH-13710)

Co-authored-by: Itay Elbirt <anotahacou@gmail.com>
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index 3816022..a98707c 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -202,6 +202,20 @@
                          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 0000000..80e2a7b
--- /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 da61db9..594f6c1 100644
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -1040,6 +1040,9 @@
                     else
                         want_escape = 1;
                 }
+                else if (c == dialect->escapechar) {
+                    want_escape = 1;
+                }
                 if (!want_escape)
                     *quoted = 1;
             }