import os
import chardet
# 获取文件编码类型
def get_encoding(file):
# 二进制方式读取,获取字节数据,检测类型
with open(file, 'rb') as f:
return chardet.detect(f.read())['encoding']
for file in os.listdir("D:\test"):
encoding = get_encoding("D:\test" + '\\' + file)
with open("D:\test" + '\\' + file, "r", encoding=encoding,errors='ignore') as f:
str1 = f.read()
print(str1)
代码是在我原需求上提取修改出来的,没再测试,不过大致思路是这样没错。
有时候就算根据txt的编码来读取一样会报错,我遇到的直接加个if判断修改encoding即可,不确定其他适用性。作为个思路参考。注意有些txt用utf-8-sig而不是utf-8。
if encoding == 'Windows-1254':
encoding = 'GB2312'
参考:python 获取文件字符编码类型_浅醉樱花雨的博客-CSDN博客_python获取文件编码
Python——with open()的用法_m0_48936146的博客-CSDN博客_python withopen