import os,shutil
from pymysql import *
import time
import chardet
def get_geshi(path):
try:
f = open(path, 'rb')
r = f.read()
# 获取文本的编码方式
f_charInfo = chardet.detect(r)
print(f_charInfo) # 输出文本格式信息
print(f_charInfo['encoding']) # 取得文本格式
geshi=f_charInfo['encoding']
# print(r.decode(f_charInfo['encoding'])) # 通过取得的文本格式读取txt
f.close()
return geshi
except:
if f:
f.close()
print('err')
def chuli():
file_dir='E:\\数据\\text'
for root, dirs, files in os.walk(file_dir):
# print(root) # 当前目录路径
# print(dirs) # 当前路径下所有子目录
# print(files) # 当前路径下所有非目录子文件
for file in files:
path = root+'/' + file
print(path)
geshi=get_geshi(path)
#读文件
with open(path, "r+", encoding=geshi) as f:
content2=f.readlines()
print(content2)
if __name__ == '__main__':
chuli()
python处理各种编码格式的txt文件
最新推荐文章于 2024-09-25 15:35:03 发布