您当前的位置:首页 > 电脑办公 > excel
| PPT | 电脑打字 | 计算机基础 | word | excel | Linux教程 |

自学教程:使用python实现批量转换文件编码格式

51自学网 2021-11-27 20:49:57
  excel
这篇教程使用python实现批量转换文件编码格式写得很实用,希望能帮到您。
使用python实现批量转换文件编码格式
 

最近在学习redis的源码,从网上下载了一份大神注释好的代码,但是文件编码格式是utf-8的使用sourcesight打开会出现乱码,sourceinsight不支持utf-8格式,网上找了一下,说需要安装插件解决,今天主要目的不是整sourceinsight,主要最近在学python,想练练手

因为是python新手,记录一下主要用到的模块和函数,加深印象

使用模块:os ,sys,codec,chardet

使用函数

sys.argv:用来获取命令行参数,sys.argv[0]标识代码本身路径

os.path :实现了操作路径的常用函数

os.path.isfile:判断是否为文件

os.path.isdir:判断是否为目录

 

os.walk:遍历目录树,返回一个三元组(root,dirs,files)

root 所指的是当前正在遍历的这个文件夹的本身的地址

dirs 是一个list,内容是该文件夹中所有的目录的名字(不包括子目录)

files 同样是list,内容是该文件夹中的所有文件(不包括子目录)

这个函数感觉有点不好理解,发现了一个大神的文章,写的特别详细,贴上链接:

http://www.cnblogs.com/herbert/archive/2013/01/07/2848892.html

os.path.join:合并了多个路径并返回

codecs.open:打开文件时将文件转换成Unicode编码,杜绝乱码,返回文件句柄

文件句柄.read:读取文件内容,文件内容从返回值返回

文件句柄.write:写文件

chardet.detect:识别文件的编码格式,返回一个字典

confidence:返回的编码格式的可能性

encoding:编码格式


 

OK,贴代码

# -*- coding: utf-8 -*-

'''
This file is order to covert file code format batch process
'''
import os
import sys
import codecs
import chardet

def GetFileExtension(file):
    (filepath, filename) = os.path.split(file)
    (shortname, extension) = os.path.splitext(filename)
    return extension

def GetFileEncodingFormat(file):
    fileHandle  = open(file, 'r', errors = 'ignore')
    fileContext = fileHandle.read()
    return chardet.detect(fileContext.encode())["encoding"]

def CovertFileCodeFormat(file, out_encode):
    try:
        encoding = GetFileEncodingFormat(file)
        extension = GetFileExtension(file)
        if (encoding != out_encode and (extension == '.c' or extension == '.h')):
            fileHandle  = codecs.open(file, 'r', encoding, errors = 'ignore')
            fileContext =  fileHandle.read()
            codecs.open(file, 'w', out_encode,  errors = 'ignore').write(fileContext)
            print ("convert:" + file + " sucess")
    except IOError as err:
        print ("I/O error: {0}".format(err))

def ProcessDir(dir):
    for root, dirs, files in os.walk(dir):
        for file in files:
            filePath = os.path.join(root, file)
            CovertFileCodeFormat(filePath, sys.argv[2])
    
def main():
    path = sys.argv[1]
    if (os.path.isfile(path)):
        CovertFileCodeFormat(path, sys.argv[2])
    elif (os.path.isdir(path)):
        ProcessDir(path)
    
if __name__ == '__main__':
    main()

python将txt等文件中的数据读为numpy数组的方法
使用python将所有csv文件从编码ansi转换为utf8
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1