• 一个批量转换文件编码的python脚本


    需要将工作目录下的文件进行转码,开始的编码是GBK的,需要将其转换为utf-8的。文件较多,手动转换肯定不行,用Python写个脚本来实现。找到一段代码参考:
    1. import os,sys  
    2.   
    3. def convert( filename, in_enc = "GBK", out_enc="UTF8" ):  
    4.     try:  
    5.         print "convert " + filename,  
    6.         content = open(filename).read()  
    7.         new_content = content.decode(in_enc).encode(out_enc)  
    8.         open(filename, 'w').write(new_content)  
    9.         print " done"  
    10.     except:  
    11.         print " error"  
    12.   
    13. def explore(dir):  
    14.     for root, dirs, files in os.walk(dir):  
    15.         for file in files:  
    16.             path = os.path.join(root, file)  
    17.             convert(path)  
    18.   
    19. def main():  
    20.     for path in sys.argv[1:]:  
    21.         if os.path.isfile(path):  
    22.             convert(path)  
    23.         elif os.path.isdir(path):  
    24.             explore(path)  
    25.   
    26. if __name__ == "__main__":  
    27.     main() 

    使用了string模块里的encode方法和decode方法,我用的是python 3.1版本,发现者两个方法已经不支持了。如果你是旧版本的Python可以直接使用,2.6是可以的。

    查阅了下3.1的文档,发现codecs能很好处理文件编码问题,使用它来正确的读出文件,然后将文件编码改为utf-8,写回去就好:
    代码实现如下:

    import os
    import sys
    import codecs
    #该程序用于将目录下的文件从指定格式转换到指定格式,默认的是GBK转到utf-8
    def convert(file,in_enc="GBK",out_enc="UTF-8"):
    try:
    print ("convert " +file)
    f=codecs.open(file,'r',in_enc)
    new_content=f.read()
    codecs.open(file,'w',out_enc).write(new_content)
    #print (f.read())
    except IOError as err:
    print ("I/O error: {0}".format(err))


    def explore(dir):
    for root,dirs,files in os.walk(dir):
    for file in files:
    path=os.path.join(root,file)
    convert(path)

    def main():
    for path in sys.argv[1:]:
    if(os.path.isfile(path)):
    convert(path)
    elif os.path.isdir(path):
    explore(path)

    if __name__=="__main__":
    main()       
  • 相关阅读:
    HDU 4772 Zhuge Liang's Password (矩阵旋转)
    POJ 1141 Brackets Sequence(区间DP)
    POJ 2531 Network Saboteur (DFS)
    HDU 2680 Choose the best route (最短路)
    HDU 1285 确定比赛名次 (预处理+拓扑排序)
    HDU 4540 威威猫系列故事——打地鼠 (DP)
    HDU 2899 Strange fuction (二分)
    HDU 3485 Count 101(DP)
    codeforces 510c (拓扑排序)
    codeforces 510B Fox And Two Dots(dfs)
  • 原文地址:https://www.cnblogs.com/macula7/p/1960395.html
Copyright © 2020-2023  润新知