[python]将txt文件编批量转为utf8
因为处理数据的需求,所以txt文件编码需要统一为utf8,windows下txt文件编码格式多为gbk。
1.基本思路
整个过程基本分为以下几个步骤,也是该脚本的主体思路
- 获取需要改变编码格式的文件夹路径
- 读取该文件夹下的txt文件,利用第三方库chardet预测编码,并将该编码格式记录
- 将该txt文件按预测的编码格式解码后,用utf8重新编码,重新写入源文件并覆盖,实现转码
- 对每一个文件重复2-3步骤,直到所有的txt都被重新编码
2.一些题外话
1. 由于事先所接收的文件编码格式多且杂乱,所以需要通过chardet预测,如预测出现问题则可能导致解码错误,重新写入时会出现乱码现象,至今未曾解决,但该bug出现频率不高,常见于文本量极小的中文文件。
2. chardet 不能精确到gb2312,所以预测结果为gb2312时,需要将其归为GBK,gb2312也确实属于GBK的子集。
3. 预测结果为utf8的文本直接不作处理
4.主体思路应该为对单个文件的预测,解码,重新编码,即gbk_2_utf8这个方法(原来的目的和实现的目标是gbk转utf8,后来编码时发现可以实现更为强大的功能,方法名就没改)。为了方便使用,套了一层循环使用的外壳,实现对某个路径下所有txt文件的预测,解码,重新编码。另外顺便加了一个可以获取路径的超超超超超简陋gui界面。
3.源码如下 || Talk is cheap,show me the code!
import os
import codecs
import chardet
import time
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter import messagebox
检验文本文件的编码格式并转为utf-8
def gbk_2_utf8(filename,out_enc="UTF-8"):
try:
content = open(filename, 'rb').read()
source_encoding = chardet.detect(content)
print("编码格式: " + source_encoding['encoding'])
if(source_encoding['encoding'] != "utf-8"):
if(source_encoding['encoding'] == 'GB2312'):
content = content.decode("GBK")
content = content.encode(out_enc)
codecs.open(filename, 'wb').write(content)
else:
content = content.decode(source_encoding['encoding']).encode(out_enc)
codecs.open(filename, 'wb').write(content)
print("转换完成")
print("*************************")
else:
print("无需转换")
print("*************************")
except IOError as err:
print("I/O error:{0}".format(err))
遍历文件夹下的所有txt文件
- def explore(dir):
for root, dirs, files in os.walk(dir):
for file in files:
if os.path.splitext(file)[1] == '.txt':
print("打开文件:"+file)
path = os.path.join(root, file)
#print(path)
gbk_2_utf8(path)
# 获取从外部选择的文件夹路径 def getpath():
def selectPath():
path_ = askdirectory()
path.set(path_)
root = Tk()
path = StringVar()
def close():
if(path.get() == ""):
messagebox.showinfo(" ","没有选择路径")
else:
root.withdraw()
root.quit()
Label(root, text="目标路径:").grid(row=0, column=0)
Entry(root, textvariable=path).grid(row=0, column=1)
Button(root, text="路径选择", command=selectPath).grid(row=0, column=2)
Button(root, text="确定", command=close).grid(row=0, column=3)
root.mainloop()
return path.get()
def main():
path = getpath()
print("选择的路径为: " + path)
print("*************************")
explore(path)
print("转换完成3秒后结束")
time.sleep(1)
print("转换完成2秒后结束")
time.sleep(1)
print("转换完成1秒后结束")
time.sleep(1)
print("转换完成,准备退出")
if __name__ == "__main__":
main()
下载地址
提供一个可以在未安装环境的windows系统下运行的版本
链接:https://pan.baidu.com/s/1gHvSLtutC41yjYrqMAHRfA 密码:uaw9
原文作者: Za_Nks
原文链接: https://www.zanks.cn/python/python-将txt文件编批量转为utf8.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
----------------------------本文结束 感谢您的阅读---------------------------