python - 将多个 CSV 文件转换为 UTF-8 编码
问题描述
我需要将多个 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
有人能帮我吗?谢谢!!!
解决方案
您需要zip
列表myFiles
并使csv_encoding
它们的值对齐:
for file, encoding in zip(myFiles, csv_encoding):
...
您需要在open()
调用中指定该值:
...
with codecs.open(file, 'r', encoding=encoding) as file_for_conversion:
注意:在 Python 3 中,不需要使用该codecs
模块来打开文件。只需使用内置open
函数并使用参数指定编码encoding
即可。
推荐阅读
- macos - 如何在不验证 TouchId、macOS Catalina 的情况下在 Safari 上启用自动填充帐户/密码?
- python - 如何通过熊猫中的两个键将数据框与自身合并?
- pine-script - 更改图表分辨率时更改线条绘制长度?
- oracle - Oracle apex Shuttle 列表的特定限制
- sql-server - SQL Server 中的第一个值?
- python - 如何在 Tkinter 中模拟 Windows 屏幕超时?
- angular - 当我添加到 component.ts 时,html 消失了
- php - 使用 PayPal Checkout API,收款人被忽略
- android - 在参数中发送整个数据类实例
- android - 如何将 Flutter 应用程序发送给客户端进行测试