python文件编码转换工具_[转]一个批量转换文本文件编码的程序(Python)

lhwork 发表于 2007-2-1 9:06:53

这个其实很简单的,用 decode() 和 和 encode 两个函数就可以搞定。

我需要的是 GB2312 跟 UTF-8 之间的转换,需要 Python 2.4 或者 Python 2.3 + CJKCodecs,要不然不支持 GB2312 的编码

用 GB2312 时,有时会出现错误,说某个字符不能识别,估计是超出了它的字符集的原因,由于 GBK 是它的扩展,索性就直接用 GBK 了。

此外就是目录遍历了,有一个非常好的工具 os.walk(),一次搞定。

完整的源代码如下: undefinedview plaincopy to clipboardprint? #!/usr/bin/python

import os,sys

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

# read the file

content = open( filename ).read()

# convert the concent

try:

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

#write to file

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

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() #!/usr/bin/python import os,sys def convert( filename, in_enc = "GBK", out_enc="UTF-8" ): # read the file content = open( filename ).read() # convert the concent try: new_content = content.decode( in_enc ).encode( out_enc ) #write to file open( filename, 'w' ).write( new_content ) 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()

这个 Blog 贴的代码实在是太难看了,可以在这里 下载。有时间一定的好好整整它,哼!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值