最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

Python批量转换文件编码格式

来源:懂视网 责编:小采 时间:2020-11-27 14:41:28
文档

Python批量转换文件编码格式

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.o
推荐度:
导读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.o

自己写的方法,适用于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()

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

文档

Python批量转换文件编码格式

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.o
推荐度:
标签: 转换 文件 批量
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top