gpt4 book ai didi

python批量修改文件编码格式的方法

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 27 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python批量修改文件编码格式的方法由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例为大家分享了python批量修改文件编码格式的具体代码,供大家参考,具体内容如下 。

使用说明:

1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下载地址:点击这里 。

2、环境配置:Python安装+配置环境变量,chardet解压放在Python安装目录\Lib\site-packages下 。

举例:批量修改当前路径下所有.cpp文件的编码格式为UTF-8,代码如下:

python:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os
import sys
import codecs
import chardet
 
def convert(filename,out_enc = "UTF-8" ):
   try :
     content = codecs. open (filename, 'r' ).read()
     source_encoding = chardet.detect(content)[ 'encoding' ]
     print source_encoding
 
     content = content.decode(source_encoding).encode(out_enc)
     codecs. open (filename, 'w' ).write(content)
   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:
       if os.path.splitext( file )[ 1 ] = = '.cpp' :
         print file
         path = os.path.join(root, file )
         convert(path)
 
def main():
   explore(os.getcwd())
 
if __name__ = = "__main__" :
   main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.

原文链接:https://blog.csdn.net/vagerant/article/details/50350171 。

最后此篇关于python批量修改文件编码格式的方法的文章就讲到这里了,如果你想了解更多关于python批量修改文件编码格式的方法的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com