首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中使用petl模块加载utf-8文件时出错

在Python中使用petl模块加载utf-8文件时出错
EN

Stack Overflow用户
提问于 2016-01-21 18:18:25
回答 1查看 443关注 0票数 1
代码语言:javascript
复制
    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将其加载到内存中?

EN

回答 1

Stack Overflow用户

发布于 2016-01-26 16:48:00

需要先使用chardet模块找出文件的编码。通过使用通用检测器函数,它遍历文件内容并根据文件中的字符返回编码。

返回一个字典,其中包含关键字'encoding‘。

代码语言:javascript
复制
   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))

如果需要不止一次,可以将文件编码的检测放入函数中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34920938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档