- UID
- 2546
- 积分
- 159
- 帖子
- 30
- 主题
- 5
- 论坛币
- 868
- 威望
- 0
- EP值
- 134
- MP值
- 0
- 阅读权限
- 50
- 注册时间
- 2015-5-9
- 在线时间
- 52 小时
- 最后登录
- 2024-10-20
|
来源链接:
https://blog.csdn.net/weixin_30621711/article/details/98361204
以下代码只处理了assic和utf8文件。其它文件编码为保险起见并未加入支持。
参数
exts 需要处理文件的扩展名
folders 需要处理的文件夹及子目录
处理目录为当前目录
运行:
添加bom头
python proc_bom.py
删除bom头
python proc_bom.py -r
运行缺少chardet报错 请查看:http://www.cnblogs.com/wangmh/p/8004451.html
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- import os;
- import sys;
- import codecs;
- import chardet;
- #获取脚本文件的当前路径
- def cur_file_dir():
- #获取脚本路径
- path = sys.path[0]
- #判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径
- if os.path.isdir(path):
- return path
- elif os.path.isfile(path):
- return os.path.dirname(path)
- #打印结果
- #pip install chardet 安装相应插件
- def procBOM(strPath,curLen, bAdd):
- newcontent = '';
- f = open(strPath, "rb");
- fcontent = f.read();
- f.close();
- printBuffer = strPath[curLen:]
- codeType = chardet.detect(fcontent)["encoding"] #检测编码方式
- printBuffer = printBuffer + " "+str(codeType)
- if codeType.lower().find('utf-8') == -1 and codeType.lower().find('ascii') == -1 :
- #非utf8文件保险起见先退出,并输出错误提示,todo后续再添加其它转码到utf8
- print printBuffer + " error OK"
- return
-
- #不需要转换,已经添加bom头
- if bAdd and fcontent[:3] != codecs.BOM_UTF8:
- print printBuffer+" add bom",
- newcontent = codecs.BOM_UTF8;
- newcontent += fcontent;
- elif not bAdd and fcontent[:3] == codecs.BOM_UTF8:
- newcontent = fcontent[3:];
- print printBuffer+" del bom",
- else:
- return;
- fnew = open(strPath, "wb+")
- fnew.write(newcontent);
- fnew.close();
- print "done"
- return
- if __name__ == "__main__":
- bAdd = True;
- exts = ['.py'];
- folders = ["GNaviInterface/search","src","tester"]
- bAdd = True;
- if(len(sys.argv) > 1 and sys.argv[1] == '-r'):
- bAdd = False;
- curLen = len(cur_file_dir())
- for folderName in folders:
- folderPath = cur_file_dir()+"/"+folderName+"/"
- #print "procBOM:folder path = "+folderPath+",add = "+str(bAdd)
- for parent,dirnames,filenames in os.walk(folderPath):
- for f in filenames:
- bTargetFile = False;
- for e in exts:
- if(f.endswith(e)):
- bTargetFile = True;
- if(bTargetFile):
- procBOM(os.path.join(parent,f),curLen, bAdd);
- #print 'file:%s add:%s' % (os.path.join(parent, f), bAdd);
复制代码
转载于:https://www.cnblogs.com/wangmh/p/8005388.html
|
|