Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Doc/library/csv.rst
Original file line number Diff line number Diff line change
Expand Up @@ -388,9 +388,11 @@ The :mod:`!csv` module defines the following constants:

.. data:: QUOTE_MINIMAL

Instructs :class:`writer` objects to only quote those fields which contain
special characters such as *delimiter*, *quotechar*, ``'\r'``, ``'\n'``
Instructs :class:`writer` objects to quote fields containing special
characters such as *delimiter*, *quotechar*, ``'\r'``, ``'\n'``
or any of the characters in *lineterminator*.
It also quotes fields starting with a space when
:attr:`~Dialect.skipinitialspace` is :const:`True`.
If *doublequote* is :const:`False` and *escapechar* is set,
the *quotechar* is escaped instead of causing the field to be quoted.

Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,21 @@ def test_write_quoting(self):
'a,1,"p,q","r""s",x!y',
quotechar='"')

def test_write_quoting_leading_spaces(self):
fields = [' a', 'b c', ' d', 'e ']
for skipinitialspace, expected in [
(True, '" a",b c," d",e '),
(False, ' a,b c, d,e '),
]:
with self.subTest(skipinitialspace=skipinitialspace):
with StringIO(newline='') as fileobj:
writer = csv.writer(fileobj, skipinitialspace=skipinitialspace)
writer.writerow(fields)
fileobj.seek(0)
reader = csv.reader(fileobj, writer.dialect)
self.assertEqual(next(reader), fields)
self.assertEqual(fileobj.getvalue(), expected + '\r\n')

def test_write_delimiter(self):
self._write_test(['a', 1, 'p,q', 'x;y'], 'a,1,"p,q",x;y')
self._write_test(['a', 1, 'p;q', 'x,y'], 'a;1;"p;q";x,y', delimiter=';')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Quote fields with leading spaces in :class:`csv.writer` when
:const:`csv.QUOTE_MINIMAL` and ``skipinitialspace=True`` are used.
5 changes: 5 additions & 0 deletions Modules/_csv.c
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,11 @@ join_append(WriterObj *self, PyObject *field, int quoted)
field_kind = PyUnicode_KIND(field);
field_data = PyUnicode_DATA(field);
field_len = PyUnicode_GET_LENGTH(field);
if (dialect->quoting == QUOTE_MINIMAL && dialect->skipinitialspace &&
field_len > 0 && PyUnicode_READ(field_kind, field_data, 0) == ' ')
{
quoted = 1;
}
}
if (!field_len && dialect->delimiter == ' ' && dialect->skipinitialspace) {
if (dialect->quoting == QUOTE_NONE ||
Expand Down
Loading