python - CSV 读取错误 : new-line character seen in unquoted field

标签 python csv

我创建了一个 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/

相关文章:

python - 从 for 循环中查找前 9 个数字的平均值,然后查找接下来的 9 个数字,依此类推

python - 用 Python 编写 P2P 聊天应用程序

java - Firefox 不会将此文件下载为 CSV

csv - Neo4j加载CSV文件

sql - 将多个分隔文本文件导入 SQL Server 数据库并自动创建表

java - 使用 OpenCSV 从 CSV 中提取特定数字

python - 如何对重复模式进行分类?

java - 从远程 Python 脚本返回值

Python - 在 PyQt4 应用程序中动态切换翻译

swift : Streaming/Writing out a CSV file