Python批量转换文件编码格式

作者:hebedich 时间:2021-10-07 05:01:22 

自己写的方法,适用于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,批量转换,文件编码格式
0
投稿

猜你喜欢

  • 让字体美起来

    2011-06-14 09:50:21
  • PHP MVC框架中类的自动加载机制实例分析

    2023-11-04 09:18:09
  • 一文详解如何使用Python批量拼接图片

    2023-08-12 04:15:37
  • php函数serialize()与unserialize()用法实例

    2023-11-19 00:53:23
  • 基于Django框架的权限组件rbac实例讲解

    2022-09-27 17:11:51
  • PHP+JS实现文件分块上传的示例代码

    2023-06-12 00:04:07
  • python实现的文件夹清理程序分享

    2021-07-20 07:58:57
  • Python数据分析之使用scikit-learn构建模型

    2023-11-10 23:19:10
  • Win7的IIS7中ASP获得的系统日期格式为斜杠的解决办法

    2012-12-04 19:57:33
  • Python语法详解之decorator装饰器

    2021-07-15 23:11:45
  • Asp 编码互转的研究和实现代码

    2011-03-30 10:44:00
  • 基于php无限分类的深入理解

    2023-11-15 04:07:39
  • 常用的数据库访问方式是什么?

    2009-11-01 15:08:00
  • 巧用缓存提高ASP应用程序的性能

    2008-03-09 15:23:00
  • 破解加密的网页代码方法

    2010-03-16 12:35:00
  • python 实现的发送邮件模板【普通邮件、带附件、带图片邮件】

    2023-10-07 00:52:22
  • 解决nohup重定向python输出到文件不成功的问题

    2024-01-01 08:24:03
  • 无组件上传图片到数据库中,asp解决方案

    2007-08-03 13:22:00
  • response.getWriter().write()向前台打印信息乱码问题解决

    2023-07-05 05:29:37
  • 快速配置PHPMyAdmin方法

    2023-07-16 07:05:20
  • asp之家 网络编程 m.aspxhome.com