Home > Backend Development > Python Tutorial > File transcoding gadget written in python

File transcoding gadget written in python

巴扎黑
Release: 2017-04-01 15:04:04
Original
1726 people have browsed it

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 -*-
'''
Copy after login

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)
Copy after login

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template