#!/usr/bin/python # -*- coding: UTF-8 -*- # @auther gaocan 809900210@qq.com import sys import os import re import codecs ''' Codec: See Python`s Standard Encodings ''' # 文件转码 def trans_file(filename, dc, ec): contents = '' with codecs.open(filename, 'r', dc) as f: contents = f.read() with codecs.open(filename, 'w', ec) as f: f.write(contents) # 文件夹下,指定文件类型的文件转码 def trans_folder(folder, dc, ec, filters): for root, dirs, files in os.walk(folder): # root 表示当前正在访问的文件夹路径 # dirs 表示该文件夹下的子目录名list # files 表示该文件夹下的文件list # 遍历文件 for f in files: filename = os.path.join(root, f) for filter in filters: if re.match(filter, filename, re.I): trans_file(filename, dc, ec) break # 遍历所有的文件夹 for d in dirs: trans_folder(os.path.join(root, d), dc, ec, filters) # argv[1]:目标文件/文件夹 # argv[2]:目标文件的原始编码 # argv[3]:转换后的文件编码 # argv[4:n]:如果指定的目标为文件夹,则需写出过滤选项,比如*.*、*.cpp、*.h,空格分隔每个过滤选项 def main(): # 至少四个参数 if len(sys.argv) < 4: return dst = sys.argv[1] dc = sys.argv[2] ec = sys.argv[3] if os.path.isdir(dst): # 文件夹 # 至少5个参数 if len(sys.argv) < 5: return filters = sys.argv[4:len(sys.argv) - 1] trans_folder(dst, dc, ec, filters) elif os.path.isfile(dst): # 文件 trans_file(dst, dc, ec) else: return if __name__ == '__main__': main()