Python实现批量处理文件的缩进和转码问题

最近把很久前的C代码传到Github上的时候,发现全部上百个源文件的代码缩进都变成了8格,而且里面的中文都出现了乱码,所以决定写个程序来批量处理所有文件的格式。这段关于转码的代码可以适用于很多场合,比如Window下默认编码是GBK,而Linux下默认编码是UTF-8,如果两者间传输的文件中出现中文,则需要进行转码。

  • 问题分析
    缩进问题是因为在之前使用vc时没有将制符表设置为4个空格,而Github上的Tab键默认显示八格。中文乱码问题是由于vc++使用的是GBK编码。

  • 解决思路
    1.缩进问题,也就是用空格替换Tab,通过Python程序读取每一行C代码,计算出对应的空格个数,添加到去除首尾空格的源字符串前构成新的一行,然后写入新的文件。
    2.乱码问题,根据Python特性,读取一行字符串后,将在内部自动解码(decode)为Unicode形式,只需要在写入时以utf-8进行编码(encode)并输出就可以实现编码的转换。注意Python输入输出的默认编码为cp936(gbk),要在打开文件时指定写入文件的编码格式。
    3.程序只需接收原始文件夹的路径,通过递归遍历将目录中所有C文件处理后输出到新的文件夹,新文件夹与源文件夹所在目录相同,且包结构完全相同。

import os, codecs

#计算该行应有的缩进空格(考虑Tab和空格混用的情况)
def count_space(st):
    count = 0
    if st == '\n':
        return 0
    for ch in st:
        if ch == '\t':
            count = count + 4
        elif ch == ' ':                             
            count = count + 1
        else:
            break
    return count    

#处理文件:1.将tab转换成相应个数的空格 2.转化为utf-8编码
def process_file(src_path, dest_path):
    #设置写入的编码方式为utf-8
    #或使用open(dest_path, 'w', encoding = 'utf8')
    with open(src_path, 'r') as fr, codecs.open(dest_path, 'w', 'utf-8') as fw:
        for line in fr.readlines():
            clean_line = line.strip()    
            n_space = count_space(line)
            i = 0
            sp = ''
            while i < n_space:
                sp = sp + ' '
                i = i + 1
            line = sp + clean_line + '\n'
            fw.write(line)

#递归遍历整个目录
def travel(src_path, dest_path, item):
    if not os.path.isdir(src_path):
        if os.path.splitext(src_path)[1] == item:
            process_file(src_path, dest_path)           #直到遇到相应文件,就进行处理
        return

    if not os.path.isdir(dest_path):                    #创建对应的目标目录
        os.mkdir(dest_path)
    #层层深入
    for filename in os.listdir(src_path):
        travel(os.path.join(src_path, filename), os.path.join(dest_path, filename), item)

if __name__ == '__main__':
    src_root = 'C:\\Users\\Administrator\\Desktop\\C-Primer-Plus'           #接收要处理的文件夹(这里直接指定)
    dest_root = src_root + '-new'                                           
    item = '.c'                                                             
    travel(src_root, dest_root, item) 

猜你喜欢

转载自blog.csdn.net/zhayujie5200/article/details/78727677