一个批量转换文本文件编码的程序(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(),一次搞定。

完整的源代码如下:

undefined view plain copy to clipboard print ?
  1. #!/usr/bin/python   
  2.   
  3. import os,sys  
  4.   
  5. def convert( filename, in_enc = "GBK", out_enc="UTF-8" ):   
  6.     # read the file   
  7.      content = open( filename ).read()   
  8.     # convert the concent   
  9.     try:   
  10.          new_content = content.decode( in_enc ).encode( out_enc )   
  11.         #write to file   
  12.         open( filename, 'w' ).write( new_content )   
  13.     except:   
  14.         print " error... "   
  15.   
  16. def explore( dir ):   
  17.     for root, dirs, files in os.walk( dir ):   
  18.         for file in files:   
  19.              path = os.path.join( root, file )   
  20.             print "convert " + path,   
  21.              convert( path )   
  22.             print " done"   
  23.   
  24. def main():   
  25.     if len( sys.argv ) > 1 :   
  26.          path = sys.argv[1]   
  27.         if os.path.isfile( path ):   
  28.              convert( path )   
  29.         elif os.path.isdir( path ):   
  30.              explore( path )   
  31.   
  32. if __name__ == "__main__":   
  33.      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 贴的代码实在是太难看了,可以在这里 下载。有时间一定的好好整整它,哼!