【发布时间】:2020-10-11 13:28:19
【问题描述】:
我需要将多个 CSV 文件(使用不同的编码)转换为 UTF-8。
这是我的代码:
#find encoding and if not in UTF-8 convert it
import os
import sys
import glob
import chardet
import codecs
myFiles = glob.glob('/mypath/*.csv')
csv_encoding = []
for file in myFiles:
with open(file, 'rb') as opened_file:
bytes_file=opened_file.read()
result=chardet.detect(bytes_file)
my_encoding=result['encoding']
csv_encoding.append(my_encoding)
print(csv_encoding)
for file in myFiles:
if csv_encoding in ['utf-8', 'ascii']:
print(file + ' in utf-8 encoding')
else:
with codecs.open(file, 'r') as file_for_conversion:
read_file_for_conversion = file_for_conversion.read()
with codecs.open(file, 'w', 'utf-8') as converted_file:
converted_file.write(read_file_for_conversion)
print(file +' converted to utf-8')
当我尝试运行此代码时,我收到以下错误: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 5057: invalid continuation byte
有人可以帮助我吗?谢谢!!!
【问题讨论】:
-
my_encoding在您的第二个 for 循环中始终具有来自第一个 for 循环的最后一个值,这不太可能是正确的。 -
好吧,当你读取文件时,指定编码。
-
问题是我有大约 20 个不同编码的 csv 文件,我需要每周将其转换为 utf-8 以便使用它们。我的想法是自动化这个过程。
-
@aline - lenz 的回复有帮助吗?如果是这样,请务必“赞成”和“接受”它。否则,请更新您的帖子,说明您尝试过的其他事情以及您被阻止的位置。