Created
July 19, 2012 10:36
-
-
Save jamiesun/3142938 to your computer and use it in GitHub Desktop.
批量转换一个目录下的文件到utf8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#codeing:utf-8 | |
import os | |
from optparse import OptionParser | |
if __name__ == "__main__": | |
usage = "usage: %prog [options] arg" | |
parser = OptionParser(usage) | |
parser.add_option("-p", "--path", dest="path",help="files path") | |
parser.add_option("-e", "--ext",dest="ext", help="file ext") | |
(options, args) = parser.parse_args() | |
cdir = options.path | |
cext = options.ext | |
if not cdir or cext: | |
parser.print_help() | |
else: | |
def convutf8(chdir): | |
for fd in os.listdir(chdir): | |
fpath = os.path.join(chdir,fd) | |
if os.path.isdir(fpath): | |
print 'convutf8 dir',fpath | |
convutf8(fpath) | |
if fd.endswith(cext): | |
try: | |
with open(fpath,'rb') as wfd: | |
print 'read gbk file',fd | |
gbk_src = wfd.read().decode('gbk') | |
print 'write utf8 file',fd | |
utf8_src = gbk_src.encode('utf-8') | |
wfd.write(utf8_src) | |
except: | |
print 'already gbk' | |
convutf8(os.path.abspath(cdir)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment