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

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

相关文章

11月编程语言排行榜 Python逆袭C#上升到第4

11月编程语言排行榜 Python逆袭C#上升到第4

TIOBE 11 月编程语言排行榜,Python 逆袭C# 曾经有一段时间,脚本语言因其易于编写和易于运行的特性,被预测在未来将发展强大。因此,Perl,Python,PHP 和 Rub...

详解【python】str与json类型转换

在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型 str转json python字符串转json对象,需要使用json模块的loads函数...

python3将视频流保存为本地视频文件

python3将视频流保存为本地视频文件

使用python3+opencv3.3.1环境将视频流保存为本地视频文件,具体内容如下 1、利用opencv中的VideoCapture类获取视频流的链接,通过cv2的方法得到该视频流的...

pygame加载中文名mp3文件出现error

pygame加载中文名mp3文件出现error

前言:  今天刚刚做了个音乐列表,但笔者发现在指定目录mp3文件名为中文时,便出现pygame.error,不能正确加载指定mp3文件.写好的代码不想再改了,来个小测试吧 pygame播...

python中使用xlrd读excel使用xlwt写excel的实例代码

python中使用xlrd读excel使用xlwt写excel的实例代码

在数据分析和运营的过程中,有非常多的时候需要提供给别人使用,提供的形式有很多种,最经常使用的是Excel, 而 数据的统计和分析采用的是 python, 使用 python 把数据存在E...