import petl as etl
file_name = 'name of file'
file_in_memory = etl.fromcsv(file_name, encoding='utf-8')
print (etl.look(file_in_memory))
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128)该文件包含导致错误的"20 Rue d‘’Estrées,75007巴黎,法国“。
我可以使用codes.open(file_name,mode='r',encoding=‘utf-8’)读取文件,但希望能够使用petl库轻松地操作csv。
有没有办法在保留字符的同时,通过petl.fromcsv将其加载到内存中?
发布于 2016-01-26 16:48:00
需要先使用chardet模块找出文件的编码。通过使用通用检测器函数,它遍历文件内容并根据文件中的字符返回编码。
返回一个字典,其中包含关键字'encoding‘。
from chardet.universaldetector import UniversalDetector
import petl as etl
detector = UniversalDetector()
file_open = open(file_name)
for line in file_open.readlines():
detector.feed(line)
if detector.done: break
detector.close()
file_open.close()
file_encoding = detector.result['encoding']
file_name = 'name of file'
file_in_memory = etl.fromcsv(file_name, encoding=file_encoding)
print (etl.look(file_in_memory))如果需要不止一次,可以将文件编码的检测放入函数中。
https://stackoverflow.com/questions/34920938
复制相似问题