Skip to content

Instantly share code, notes, and snippets.

@jamiesun
Created July 19, 2012 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiesun/3142938 to your computer and use it in GitHub Desktop.
Save jamiesun/3142938 to your computer and use it in GitHub Desktop.
批量转换一个目录下的文件到utf8
#!/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