Python实现批量转换文件编码的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现批量转换文件编码的方法。分享给大家供大家参考。具体如下:

这里将某个目录下的所有文件从一种编码转换为另一种编码,然后保存

import os
import shutil
def match(config,fullpath,type):
  flag=False
  if type == 'exclude':
    for item in config['src']['exclude']:
      if fullpath.startswith(config['src']['path']+os.path.sep+item):
        flag=True
        break
  if type=='filter':
    for item in config['src']['filter']:
      if fullpath.endswith(item):
        flag=True
        break
  return flag
def conver_file(param):
  for root, dirs, files in os.walk(param['src']['path']):
    for filename in files:
      readfile=root+os.path.sep+"%s" %filename
      print(readfile)
      if 'filter' in param['src']:
        if not (match(param,readfile,'filter')):
          continue
      s=''
      outfile=readfile.replace(param['src']['path'],param['dest']['path'])
      try :
        s=open(readfile,encoding=param['src']['encoding']).read()
      except:
        print("file %s read erro" % readfile)
        shutil.copy(readfile,outfile)
      if s: #False and
        print("save")
        with open(outfile, mode='w', encoding=param['dest']['encoding']) as a_file:
          a_file.write(s)
    for dirname in dirs:
      file=root+os.path.sep+"%s" %dirname
      if 'exclude' in param['src']:
        if(match(param,file,'exclude')):
          continue
      outdir=file.replace(param['src']['path'],param['dest']['path'])
      #print(outdir)
      if not os.path.isdir(outdir):
        os.mkdir(outdir)
if __name__ == "__main__":
  param={'src':{'path':r'D:\work\test\trunk','encoding':'gbk','exclude':['dataa'],'filter':['.php','.html','.htm']},
    'dest':{'path':"f:\\test\\new",'encoding':'utf-8'}}
  conver_file(param)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

利用Django-environ如何区分不同环境

介绍 Django是一个Web框架——一套用于帮助开发交互式网站的工具。Django能够响应网页请求,还能让我们更轻松地读写数据库、管理用户等。本文主要介绍了关于利用Django-env...

大家都说好用的Python命令行库click的使用

一、前言 在本系列前面几篇文章中,我们分别介绍了 argparse 和 docopt 的主要功能和用法。它们各具特色,都能出色地完成命令行任务。argparse 是面向过程的,需要先设...

Python程序员面试题 你必须提前准备!(答案及解析)

Python程序员面试题 你必须提前准备!(答案及解析)

在发布《Python程序员面试,这些问题你必须提前准备!》一文后,应广大程序员朋友的强烈要求,小编就Python程序员面试必备问题整理了一份参考答案,希望能对准备换工作的程序员朋友有所帮...

解决Spyder中图片显示太小的问题

最近在做机器学习的作业,需要画决策树。在Spyder中把代码跑了一遍,发现决策树出现在了Spyder的console中,而且图片很小,那些字体都叠在一起。网上搜了一圈好像也没找到解决方案...

解决pytorch DataLoader num_workers出现的问题

解决pytorch DataLoader num_workers出现的问题

最近在学pytorch,在使用数据分批训练时在导入数据是使用了 DataLoader 在参数 num_workers的设置上使程序出现运行没有任何响应的结果 ,看看代码 import...