首页 > 解决方案 > python读取csv受utf-8编码干扰

问题描述

我试图在 python 中使用 pandas 读取 csv 文件,后来我试图读取一个文本文件并用 csv 中的值替换内容我得到以下错误:

 lines = [line.decode('utf-8').strip() for line in lines]
  File "/usr/local/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 140: invalid start byte

标签: pythonpandasutf-8

解决方案


尝试在下面使用。它以一种非常简单的方式对我有用。

 str= str.decode('unicode_escape').encode('utf-8') 

如果您正在阅读文本文件,那么在这里您需要遍历列表的每个元素,您可以尝试以下操作

lines= open("file.text", "r")
lines = fileread.readlines()
lines = [line.decode('unicode_escape').encode('utf-8') for line in lines]

希望这可以帮助...


推荐阅读