Python實現批量處理檔案的縮排和轉碼問題
阿新 • • 發佈:2019-02-07
最近把很久前的C程式碼傳到Github上的時候,發現全部上百個原始檔的程式碼縮排都變成了8格,而且裡面的中文都出現了亂碼,所以決定寫個程式來批量處理所有檔案的格式。這段關於轉碼的程式碼可以適用於很多場合,比如Window下預設編碼是GBK,而Linux下預設編碼是UTF-8,如果兩者間傳輸的檔案中出現中文,則需要進行轉碼。
問題分析
縮排問題是因為在之前使用vc時沒有將制符表設定為4個空格,而Github上的Tab鍵預設顯示八格。中文亂碼問題是由於vc++使用的是GBK編碼。解決思路
1.縮排問題,也就是用空格替換Tab,通過Python程式讀取每一行C程式碼,計算出對應的空格個數,新增到去除首尾空格的源字串前構成新的一行,然後寫入新的檔案。
2.亂碼問題,根據Python特性,讀取一行字串後,將在內部自動解碼
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)