您的位置:首页 > 编程语言 > Python开发

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

2010-08-22 00:32 543 查看
需要将工作目录下的文件进行转码,开始的编码是GBK的,需要将其转换为utf-8的。文件较多,手动转换肯定不行,用Python写个脚本来实现。找到一段代码参考:

import os,sys  

  

def convert( filename, in_enc = "GBK", out_enc="UTF8" ):  

    try:  

        print "convert " + filename,  

        content = open(filename).read()  

        new_content = content.decode(in_enc).encode(out_enc)  

        open(filename, 'w').write(new_content)  

        print " done"  

    except:  

        print " error"  

  

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() 

使用了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()       
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐