Python批量转换文件编码格式

yipeiwu_com5年前Python基础

自己写的方法,适用于linux,

#!/usr/bin/python
#coding=utf-8
import sys
import os, os.path
import dircache
import commands
def add(x,y):
 return x*y

def trans(dirname):
 lis = dircache.opendir(dirname)
 for a in lis:
af=dirname+os.sep+a
## print af
 if os.path.isdir(af):
## print af
trans(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())

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的版本

import os
import sys
import codecs
#该程序用于将目录下的文件从指定格式转换到指定格式,默认的是GBK转到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())
except IOError as err:
print ("I/O error: {0}".format(err))


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

以上所述就是本文 的全部内容了,希望大家能够喜欢。

相关文章

解决python3 安装完Pycurl在import pycurl时报错的问题

此次遇到的问题是在import pycurl 时报错 pycurl:libcurl link-time version is older than compile-time versi...

python自动12306抢票软件实现代码

昨天我发的是抓取的12306数据包,然后分析了一下,今天按照昨天的分析 用代码实现了,如果有需要的同学们可以看一下,实现的功能有,登录,验证码识别,自动查票,有余票点击预定, 差了最后一...

使用IPython下的Net-SNMP来管理类UNIX系统的教程

引言 对于简单网络管理协议 (SNMP),大多数系统管理员都具有一定的使用经验,或者至少听说过它。如果您正在一个数据中心工作,那么您每天都可能采用某种方式与 SNMP 进行交互。有许多给...

Python多线程结合队列下载百度音乐的方法

本文实例讲述了Python多线程结合队列下载百度音乐的方法。分享给大家供大家参考。具体如下: 一直想做个下载音乐的脚本,后来决定就拿百度音乐开刀,经过多次分析,终于制作了一个下载百度音乐...

Python的Django框架中设置日期和字段可选的方法

设置字段可选 在摆弄了一会之后,你或许会发现管理工具有个限制:编辑表单需要你填写每一个字段,然而在有些情况下,你想要某些字段是可选的。 举个例子,我们想要Author模块中的email字...