如何使用 DictReader 以通用换行模式访问原始 csv 内容?

How to access raw csv content in universal-newline mode using DictReader?

我有这些代码行:

>>> import csv, io
>>> raw_csv = io.StringIO('one,two,three\r1,2,3\r,1,2,3')
>>> reader = csv.DictReader(raw_csv, delimiter=',')
>>> list(reader)

导致错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../lib/python3.9/csv.py", line 110, in __next__
    self.fieldnames
  File ".../lib/python3.9/csv.py", line 97, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

我发现 solutionsopen() 一起使用,但我无法使用它,因为没有文件路径。我还需要使用 DictReader.

您可以将 newline='' 传递给 StringIO constructor 以启用通用换行模式:

>>> reader = csv.DictReader(StringIO(file), delimiter=',')
>>> next(reader)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/csv.py", line 110, in __next__
    self.fieldnames
  File "/usr/lib/python3.10/csv.py", line 97, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

>>> reader = csv.DictReader(StringIO(file, newline=''), delimiter=',')
>>> next(reader)
{'one': '1', 'two': '2', 'three': '3'}