简体   繁体   English

如何在读取csv文件时修复非法换行值

[英]How to fix an illegal newline value when reading a csv file

I have had trouble reading a .csv file using Python 3.7. 我在使用Python 3.7读取.csv文件时遇到了麻烦。 When I wrote: 我写的时候:


import csv
with open ('iris.csv', newline =' ') as csv_file:
    rows = csv.reader(csv_file)
    for row in rows:
        print(row)

and ran the code, it just says: 并运行代码,它只是说:

ValueError                                Traceback (most recent call last)
<ipython-input-2-42d17202da4e> in <module>()
      1 import csv
----> 2 with open ('iris.csv', newline =' ') as csv_file:
      3     rows = csv.reader(csv_file)
      4     for row in rows:
      5         print(row)

ValueError: illegal newline value:  

How can I fix this problem? 我该如何解决这个问题? And why is ' ' has an illegal value? 为什么''具有非法价值? I expcted it would be like: 我表示它会像:

['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
['5.1', '3.5', '1.4', '0.2', 'setosa']
['4.9', '3', '1.4', '0.2', 'setosa']
['4.7', '3.2', '1.3', '0.2', 'setosa']
['4.6', '3.1', '1.5', '0.2', 'setosa']

Thanks! 谢谢!

From the docs : https://docs.python.org/3/library/functions.html#open 来自文档: https//docs.python.org/3/library/functions.html#open

newline controls how universal newlines mode works (it only applies to text mode). 换行符控制通用换行模式的工作方式(仅适用于文本模式)。 It can be None, '', '\\n', '\\r', and '\\r\\n'. 它可以是None,'','\\ n','\\ r'和'\\ r \\ n'。

In your case, newline =' ' is invalid since it is not one of the characters listed in the values in the docs. 在您的情况下, newline =' '无效,因为它不是文档中值中列出的字符之一。

I think you got confused with a csv delimiter in csv.reader , which is what separates two values in a csv file 我认为你与csv.reader中的csv delimiter混淆了,这是csv文件中两个值的分隔

Dialect.delimiter Dialect.delimiter
A one-character string used to separate fields. 用于分隔字段的单字符字符串。 It defaults to ','. 它默认为','。

Example

a,b,c,d
e,f,g,h

Based on what your delimiter is, you can specify that in the delimiter field while reading the csv 根据您的分隔符,您可以在读取csv时在delimiter字段中指定

rows = csv.reader(csv_file, delimiter="<your_delimiter>")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM