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

一个批量转换文本文件编码的程序(Python)

2014-12-17 00:40 344 查看


一个批量转换文本文件编码的程序(Python)

#!/usr/bin/python

import os,sys

def convert( filename, in_enc = "GBK", out_enc="UTF-8" ):

# read the file

fp = open( filename )

content = fp.read()

fp.close()

# convert the concent

try:

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

#write to file

fp = open( filename, 'w' )

fp.write( new_content )

fp.close()

except:

print " error... "

def explore( dir ):

for root, dirs, files in os.walk( dir ):

for file in files:

path = os.path.join( root, file )

print "convert " + path,

convert( path )

print " done"

def main():

if len( sys.argv ) > 1 :

path = sys.argv[1]

if os.path.isfile( path ):

convert( path )

elif os.path.isdir( path ):

explore( path )

if __name__ == "__main__":

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