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

作者:yak 时间:2023-06-02 20:03:49 

本文实例讲述了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程序设计有所帮助。

标签:Python,转换,编码
0
投稿

猜你喜欢

  • Python hashlib模块详细讲解使用方法

    2021-09-11 12:08:16
  • 小白讲座:在win下mysql备份恢复命令概括

    2009-09-05 09:43:00
  • python中pivot()函数基础知识点

    2023-12-18 15:28:06
  • tensorflow使用神经网络实现mnist分类

    2023-07-05 10:19:13
  • Django中使用haystack+whoosh实现搜索功能

    2021-10-12 23:54:14
  • Python要求O(n)复杂度求无序列表中第K的大元素实例

    2023-07-30 13:18:01
  • Python离线安装包教程分享

    2023-08-03 18:16:40
  • 如何把图片也存到数据库中去?

    2009-11-06 13:56:00
  • django实现登录时候输入密码错误5次锁定用户十分钟

    2023-04-17 14:48:57
  • Python通过yagmail实现发送邮件代码解析

    2022-12-31 13:44:58
  • 指导:SQL Server无日志恢复数据库

    2009-02-20 17:07:00
  • 使用JS+XML(数据岛)实现分页)

    2005-08-18 00:46:06
  • Python对两个有序列表进行合并和排序的例子

    2022-06-07 00:11:37
  • go语言中值类型和指针类型的深入理解

    2024-04-28 09:18:29
  • Go代码检查的推荐工具及使用详解

    2024-05-09 15:00:11
  • 微信小程序wxml列表渲染原理解析

    2023-07-17 14:28:08
  • python正则表达式re.group()用法

    2021-08-17 03:31:03
  • 微信跳一跳自动运行python脚本

    2023-11-22 01:42:29
  • vuex页面刷新数据丢失问题的四种解决方式

    2024-04-09 10:58:50
  • Python二进制数据结构Struct的具体使用

    2022-07-10 00:01:59
  • asp之家 网络编程 m.aspxhome.com