Python batch conversion file encoding format

Source: Internet
Author: User
You need to transcode the files in the working directory. the encoding starts from GBK and needs to be converted to UTF-8. There are many files, but manual conversion is definitely not feasible. use Python to write a script for implementation. Self-written method, applicable to linux,

#!/usr/bin/python#coding=utf-8import sysimport os, os.pathimport dircacheimport commandsdef add(x,y): return x*ydef trans(dirname): lis = dircache.opendir(dirname) for a in lis:af=dirname+os.sep+a## print af if os.path.isdir(af):## print aftrans(af)else: ## print af+"encoding="+fi.name ft = commands.getoutput('file -i '+af)## print ft if a.find('.htm')==-1 and a.find('.xml')==-1 and ft.find('text/')!=-1 and ft.find('iso-8859')!=-1: print 'gbk'+ft+">"+af commands.getoutput('iconv -ficonv -f gbk -t utf-8 -c -o'+""+af+""+af)trans(os.getcwd())

Available code for versions earlier than py2.6

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

Py3.1 version is supported.

Import osimport sysimport codecs # This program is used to convert files in the directory from the specified format to the specified format. the default value is GBK to 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 () handle T IOError as err: print ("I/O error: {0 }". format (err) def inclue (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): Export E (path) if _ name __= = "_ main _": main ()

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.