python批量GBK转UTF-8
2015-12-16 14:58
197 查看
有时候编码问题在导入工程的时候很烦,所以还是让世界都是"UTF-8"吧。
抄来一段代码:
抄来一段代码:
#!/usr/env python # -*- coding: utf8 -*- import fnmatch import os import sys import codecs import chardet def find_files(path, fnexp="*"): for root, dirs, files in os.walk(path): for filename in fnmatch.filter(files, fnexp): yield os.path.join(root, filename) def ReadFile(filePath,encoding="gbk"): with codecs.open(filePath,"r",encoding) as f: return f.read() def WriteFile(filePath,u,encoding="utf-8"): with codecs.open(filePath,"w",encoding) as f: f.write(u) def GBK_2_UTF8(src,dst): content = ReadFile(src,encoding="gbk") WriteFile(dst,content,encoding="utf-8") def UTF8_2_GBK(src,dst): content = ReadFile(src,encoding="utf-8") WriteFile(dst,content,encoding="gbk") def trans(fpath): for fn in find_files(fpath): print fn d = chardet.detect(open(fn,"r").read()) print d if d['encoding'] != 'utf-8': GBK_2_UTF8(fn,fn) print "ok" if __name__ == '__main__': if len(sys.argv) > 1 : for fpath in sys.argv[1:]: trans(fpath) else: fpath = raw_input("path:") trans(fpath)
相关文章推荐
- 【Python 1】函数模块
- python循环技巧
- Python文件I/O
- [No000066]python各种类型转换-int,str,char,float,ord,hex,oct等
- [No000065]python 获取当前时间
- python监控服务器信息
- SubLime Text3 打造Python的IDE
- Python小技巧:使用*解包和itertools.product()求笛卡尔积
- python-列表式实战
- Python学习笔记(2)装饰器
- python 文件读取
- python中 encode,decode,unicode,utf-8
- 【python】pip的使用
- 最小生成树,普里姆算法(Python实现)
- Python
- 使用Python抓取google街景照片
- Python学习笔记(3):web初步
- 【Python 0】初识Python
- LeetCode Palindrome Number
- python2中新式类和旧式类的对比【译】