我创建了一个 python 脚本,它使用包含 10 条记录的测试 CSV 数据集。当我将其扩展到实际数据集(几千行)时,出现以下错误:
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
代码如下:
with open('./Origins.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
origincoords = ['{Y},{X}'.format(**row) for row in reader]
完整的错误代码是:
Traceback (most recent call last):
File "./Driving.py", line 14, in <module>
origincoords = ['{Y},{X}'.format(**row) for row in reader]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 103, in next
self.fieldnames
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 90, in fieldnames
self._fieldnames = self.reader.next()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
也许我使用的 CSV 读取方法存在比例问题?
最佳答案
来自 PEP-0278 :
In a Python with universal newline support open() the mode parameter can also be "U", meaning "open for input as a text file with universal newline interpretation". Mode "rU" is also allowed, for symmetry with "rb"
所以努力改变
with open('./Destinations.csv', 'r') as csvfile:
到
with open('./Destinations.csv', 'rb') as csvfile:
如果错误仍然存在,请更改为
with open('./Destinations.csv', 'rU') as csvfile:
根据 Martijn Pieters 的评论进行编辑。
关于python - CSV 读取错误 : new-line character seen in unquoted field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26102302/