阅读csv文件的python错误
with open('repo-attributes.csv', 'rb') as repofile:
reader = csv.DictReader(repofile)
for repo in reader:
g.add_vertex(name=repo['repository_url'],
label=repo['repository_url'][19:],
language='(unknown)' if repo['repository_language'] == 'null'
else repo['repository_language'],
watchers=int(repo['repository_watchers']))
这是我的代码。 我收到如下错误。我是python的新手。请好好解释一下。阅读csv文件的python错误
Traceback (most recent call last):
File "C:\Python34\github-network-analysis-master\process.py", line 9, in <module>
for repo in reader:
File "C:\Python34\lib\csv.py", line 109, in __next__
self.fieldnames
File "C:\Python34\lib\csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
删除b
,你打开二进制模式因此bytes
错误:
with open('repo-attributes.csv', newline="") as repofile:
实际上,你可以删除这两个作为默认模式是r
。
OP应该添加'newline ='''以及。请参阅['csv.reader()'文档](https://docs.python.org/3/library/csv.html#csv.reader)。他们很可能会阅读关于使用'csv.reader()'和* Python 2 *的文章,其中建议使用''rb''。 – 2015-02-23 15:28:40
@MartijnPieters,在处理DictReader时,我没有看到与换行符有关的任何东西。 – 2015-02-23 15:31:57
'DictReader()'只是'csv.reader()'的一个包装。 – 2015-02-23 15:32:24
您正在打开的文件在rb
意味着read binary
请打开它在read
模式。将您的代码更改为
...
...
with open('repo-attributes.csv', 'r')...
...
...
这将在read
模式(非二进制)中打开文件。
跟踪的最后一行告诉错误首先发生的位置。 由于您以二进制模式打开文件,因此python正在读取字节。您的文件是csv并以读模式打开它就足够了。
所以,而不是rb使用r
真的错误是自我解释。你用'rb'标志打开了一个文件,这意味着在读取二进制模式下打开。你只需要只读的'r'标志。 – ljetibo 2015-02-23 14:52:58
使用''rb''是运行Python 2时要做的正确事情;在Python 3中,[module documentation](https://docs.python.org/3/library/csv.html)中的建议是使用''r''和'newline ='''。 – 2015-02-23 15:27:45
也许与此处有关:[如何阻止Python的csv.DictWriter.writerows在Windows中的行之间添加空行?](http://stackoverflow.com/q/22361787) – 2015-02-23 15:34:57