python 读入csv 出现utf-8 错误

在解析csv文件的时候出现报错:

'utf-8' codec can't decode byte 0xff in position 0

这说明此csv是binary文件,你应该将它转换为utf-8就能被python读取。

或者参考以下方式读取(但是这样不能使用诸如strip(), split()等str的函数,因为读出来是binary文件)

https://stackoverflow.com/questions/42339876/error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-in

原文:

错误写法:
 image_data = tf.gfile.FastGFile(image, 'r').read()
解决:

#读取图片(文件在下)
“`
image_data = tf.gfile.FastGFile(image, ‘rb’).read()


参考:
https://stackoverflow.com/questions/42339876/error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-in
Python tries to convert a byte-array (a bytes which it assumes to be a utf-8-encoded string) to a unicode string (str). This process of course is a decoding according to utf-8 rules. When it tries this, it encounters a byte sequence which is not allowed in utf-8-encoded strings (namely this 0xff at position 0).

Since you did not provide any code we could look at, we only could guess on the rest.

From the stack trace we can assume that the triggering action was the reading from a file (contents
 = open(path).read()). I propose to recode this in a fashion like this:

with open(path, ‘rb’) as f:
contents = f.read()

“`
==That b in the format specifier in the open() states that the file shall be treated as binary, so contents will remain a bytes. No decoding attempt will happen this way.==

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 CSV 文件转换为 UTF-8 编码格式,并读入 Pandas DataFrame 中,可以按照以下步骤操作: 1. 使用 Pandas 的 `read_csv` 函数读取 CSV 文件。例如: ``` import pandas as pd df = pd.read_csv('file.csv', encoding='原始编码格式') ``` 在这个示例中,我们使用了 Pandas 的 `read_csv` 函数将 CSV 文件读入到一个 Pandas DataFrame 中,并指定了 CSV 文件的原始编码格式。 2. 将读入的数据转换为 UTF-8 编码格式。例如: ``` import pandas as pd df = pd.read_csv('file.csv', encoding='原始编码格式') df = df.applymap(lambda x: x.encode('utf-8').decode('utf-8')) ``` 在这个示例中,我们使用了 Pandas DataFrame 对象的 `applymap` 方法,将 DataFrame 中的每一个元素都转换为 UTF-8 编码格式。 3. 对转换后的数据进行处理或者写入新的 CSV 文件。例如: ``` import pandas as pd df = pd.read_csv('file.csv', encoding='原始编码格式') df = df.applymap(lambda x: x.encode('utf-8').decode('utf-8')) # 对数据进行处理 # ... # 将处理后的数据写入新的 CSV 文件 df.to_csv('new_file.csv', index=False, encoding='utf-8') ``` 在这个示例中,我们对转换后的数据进行了一些处理,然后使用 Pandas DataFrame 对象的 `to_csv` 方法将处理后的数据写入到一个新的 CSV 文件中。需要注意的是,我们在写入文件时指定的编码格式为 UTF-8,并将 `index` 参数设置为 `False`,以避免写入的数据中出现多余的行号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值