import csv
with open (r’C:\Users\jacky\Desktop\test\test.csv’,‘rb’) as myfile:
lines =csv.reader(myfile)
for line in lines:
print(line)

出现报错:
Traceback (most recent call last):
File “c:/Users/jacky/Desktop/test/practice0514.py”, line 4, in
for line in lines:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

百度翻译了一下:
_Error:迭代器应该返回字符串,而不是字节(是否以文本模式打开文件?)

查询一下open()函数:
报错:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)python open()函数总结

因为此csv文件并非二进制文件, 只是一个文本文件
应该使用‘r’,而不是‘rb’

代码该成‘r’,报错解决了。

import csv
with open (r’C:\Users\jacky\Desktop\test\test.csv’,‘r’) as myfile:
lines =csv.reader(myfile)
for line in lines:
print(line)

说明:虽然读取方式的问题解决了,但这个代码中仍然有问题,后边将继续解析。

相关文章: