突然翻出了之前写的一份代码,适用于批量修改一个目录及其子目录下所有指定类型的文件编码。使用了python的chardet
和codecs
库。
# -*- coding: utf-8 -*-
import os, chardet, codecs, re
#文件类型扩展名 文件列表
FileType, FileList = [], []
def get_file_list(Dir):
""" 获取指定目录下所有指定类型文件
"""
if len(Dir.strip(' ')) == 0:
return
dirList = [os.path.join(Dir, f) for f in os.listdir(Dir)]
fileList = [f for f in dirList if os.path.isfile(f) and os.path.splitext(f)[1] in FileType]
folderList = [f for f in dirList if os.path.isdir(f)]
FileList.extend(fileList)
# 递归字文件夹
for subfolder in folderList:
get_file_list(subfolder)
def convert_2_target_coding(coding='utf-8'):
""" 转换成目标编码格式
"""
for filepath in FileList:
with open(filepath, 'rb') as f:
data = f.read()
codeType = chardet.detect(data)['encoding']
if codeType not in (coding, 'ascii'):
with codecs.open(filepath, 'r', codeType) as f:
content = f.read()
with codecs.open(filepath, 'w', coding) as f:
f.write(content)
print(filepath + '\n')
if __name__ == '__main__':
# 获取目录
WorkDir = str(input('input target folder\n\t:'))
# 目标编码格式
TargetCoding = str(input('target coding(default to utf-8)\n\t:')).lower()
# 文件类型扩展名
FileType = re.split(r'\s+', str(input('file type(filename extension, such as .c .h)\n\t:')))
os.chdir(WorkDir)
get_file_list(WorkDir)
convert_2_target_coding(TargetCoding)
使用方法:
- 直接启动脚本,按照提示,第一步输入目标目录的据对路径(Windows下直接拖拽到控制台);第二步输入目标编码格式,比如
utf-8
或者gb2312
什么的;第三步输入目标类型文件扩展名,如果有多个就用空格隔开,例如.py .cpp .h
- 如果要经常用的话建议拿
pyinstaller
打包一下,添加到环境变量里面~