Home > Article > Backend Development > File transcoding gadget written in python
source insight does not support utf-8. In order to support Chinese display, I wrote a pythonsmall program to convert all files in a directory from utf-8 to gbk
The code is as follows:
#!/usr/local/bin/python # -*- coding: utf-8 -*- '''
source insight unexpectedly It does not support utf-8. In order to support Chinese display, I wrote this program
to convert all files in a certain directory from utf-8 to gbk
usage: chmod +x convert.py ./convert.py src mysrc ''' import os import shutil import re import sys ##################################### def search(src,dest,handler): filelist=os.listdir(src) for f in filelist: cf=src+'/'+f df=dest+'/'+f if os.path.isdir(cf): if not os.path.exists(df): os.makedirs(df) search(cf,df,handler) else: handler(cf,df)#the function dealing with file ########################################################## def convertFile(sfn,dfn): sf=open(sfn,'r') s=sf.read() try: s=s.decode('utf-8') df=open(dfn,'w') df.write(s.encode('gbk')) df.flush() sf.close() df.close() print '*** ',sfn except: sf.close() print sfn sys.exit() if name == 'main': srcDir=os.getcwd()+'/'+sys.argv[1] dstDir=os.getcwd()+'/'+sys.argv[2] search(srcDir,dstDir,convertFile)
The above is the content of the file transcoding gadget written in python, and more For more related content, please pay attention to the PHP Chinese website (www.php.cn)!