批量将文件编码改为UTF8的python小程序

import os
from chardet import detect

fns = []
filedir = os.path.join(os.path.abspath('.'), "2utf-8")
file_name = os.listdir(os.path.join(os.path.abspath('.'), "2utf-8"))
for fn in file_name:
    if fn.endswith('.txt'):  # 这里填文件后缀
        fns.append(os.path.join(filedir, fn))

for fn in fns:
    with open(fn, 'rb+') as fp:
        content = fp.read()
        codeType = detect(content)['encoding']
        content = content.decode(codeType, "ignore").encode("utf8")
        fp.seek(0)
        fp.write(content)
        print(fn, ":已修改为utf8编码")

步骤:

1、将需要修改编码的文件(如txt文件)和此py文件放在同一目录下

2、修改程序第八行的后缀名,将其改为你想修改的文件的后缀名,此行if的目的是避免影响本文件

3、保存后执行程序

注:文件大的话跑得比较慢,请耐心等待

猜你喜欢

转载自blog.csdn.net/Lee0_King/article/details/81782317