python问题求助
from csv import DictReaderdata_rdr = DictReader(open('mn.csv','rb'))
header_rdr = DictReader(open('mn_headers.csv','rb'))
data_rows =
header_rows =
print(data_rows[:5])
print(header_rows[:5])
python报错,求助
runfile('C:/Users/Administrator/Desktop/新建文件夹/7.2.1找出需要清洗的数据.py', wdir='C:/Users/Administrator/Desktop/新建文件夹')
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\新建文件夹\7.2.1找出需要清洗的数据.py", line 13, in <module>
data_rows =
File "C:\Users\Administrator\Desktop\新建文件夹\7.2.1找出需要清洗的数据.py", line 13, in <listcomp>
data_rows =
File "D:\Anaconda3\lib\csv.py", line 110, in __next__
self.fieldnames
File "D:\Anaconda3\lib\csv.py", line 97, in fieldnames
self._fieldnames = next(self.reader)
Error: iterator should return strings, not bytes (did you open the file in text mode?) 试试 将 "rb"改成 "rt" qq1151985918 发表于 2021-4-3 10:46
试试 将 "rb"改成 "rt"
出现了这个错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0x9d in position 2817: illegal multibyte sequence 江晓夜 发表于 2021-4-3 10:53
出现了这个错误
换完之后 打开文件的两个语句改为下面这样试试
data_rdr = DictReader(open('mn.csv' , encoding='UTF-8'))
header_rdr = DictReader(open('mn_headers.csv , encoding='UTF-8')) 江晓夜 发表于 2021-4-3 10:53
出现了这个错误
那就再加一句 encoding = 'utf-8' 本帖最后由 jackz007 于 2021-4-3 11:58 编辑
Python 文本文件的编、解码问题着实是一件让人头疼的事情,楼主试试这个代码吧,新定义的函数 readfile() 可以自动尝试按 'GBK' 和 'UTF-8' 两种编码来读入 CSV 文件。
from csv import DictReader
import sys
def readfile(fn):
r = ''
fp = open(fn , 'rb')
b = fp . read()
fp . close()
e = True
try:
t = b . decode('GBK')
except:
try:
t = b . decode('UTF-8')
except:
sys . stderr . write('*** 错误,无法按照文本读取文件 : ' + fn + '\n')
e = False
if e:
r = t . split('\n')
return r
data_rdr = DictReader(readfile('mn.csv))
header_rdr = DictReader(readfile('mn_headers.csv'))
data_rows =
header_rows =
print(data_rows[:5])
print(header_rows[:5]) jackz007 发表于 2021-4-3 11:30
打开文件的两个语句改为下面这样试试
非常感谢
页:
[1]