简体   繁体   English

读取csv文件时出现python错误

[英]python error reading a csv file

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']))

This is my code. 这是我的代码。 I am getting the error like as follows. 我得到的错误如下。 I am new to python. 我是python的新手。 kindly explain this. 请解释一下。

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?)

Remove b , you are opening in binary mode hence the bytes error: 删除b ,你以二进制模式打开因此bytes错误:

 with open('repo-attributes.csv', newline="") as repofile:

You can actually remove both as the default mode is r . 您可以实际删除两者,因为默认模式是r

You are opening file in rb means read binary please open it in read mode. 你在rb中打开文件意味着read binary请在read模式下打开它。 change your code to 将您的代码更改为

...
...
with open('repo-attributes.csv', 'r')...
...
...

This will open file in read mode (not binary). 这将以read模式打开文件(非二进制)。

The last line of the trace tells where the error first occurred. 跟踪的最后一行告诉错误首次发生的位置。 Since you opened the file in binary mode, python is reading bytes. 由于您以二进制模式打开文件,因此python正在读取字节。 Your file is csv and opening it in read mode will suffice. 您的文件是csv并在读取模式下打开它就足够了。

So instead of rb use r 所以代替rb使用r

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

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