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

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

相关文章

python pygame实现挡板弹球游戏

python pygame实现挡板弹球游戏

学了一天pygame,用python和pygame写一个简单的挡板弹球游戏 GitHub: EasyBaffleBallGame # -*- coding:utf-8 -*- fr...

python在线编译器的简单原理及简单实现代码

python在线编译器的简单原理及简单实现代码

我们先来看一下效果(简单的写了一个): 原理:将post请求的代码数据写入了服务器的一个文件,然后用服务器的python编译器执行返回结果 实现代码: #flaskrun...

Python ZipFile模块详解

Python zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要...

python实现多层感知器MLP(基于双月数据集)

python实现多层感知器MLP(基于双月数据集)

本文实例为大家分享了python实现多层感知器MLP的具体代码,供大家参考,具体内容如下 1、加载必要的库,生成数据集 import math import random impor...

Python处理时间日期坐标轴过程详解

Python处理时间日期坐标轴过程详解

1. 前言 当日期数据作为图表的坐标轴时通常需要特殊处理,应为日期字符串比较长,容易产生重叠现象 2. 设定主/次刻度 2.1 引用库 from matplotlib.date...