• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python批量转换文件编码格式

python 搞代码 4年前 (2022-01-09) 14次浏览 已收录 0个评论

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

#!/usr/bin/python#coding=utf-8import sysimport os, os.pathimport dircacheimport commandsdef add(x,y): return x*ydef trans(dirname): lis = dircache.opendir(dirname) for a in lis:af=dirname+os.sep+a## print af if os.path.isdir(af):## print aftrans(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 osimport sysimport 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()

本文来源gaodai.ma#com搞##代!^码7网

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python批量转换文件编码格式
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址