功能:递归整个目录查找所有的".c" 和 ".h"文件。并将文件中的所有"#define"替换为“#define ”。
注意:"#define" 替换后有一个空格"#define "。
#!/usr/bin/env python
import os
import re
import sys
file_type_list = ['c', 'h']
#get all files
def get_file_list(dir):
filelist = []
for dirpath,dirnames,filenames in os.walk(dir):
for file in filenames:
file_type = file.split('.')[-1]
if (file_type in file_type_list):
file_fullname = os.path.join(dirpath,file)
filelist.append(file_fullname)
return filelist
if __name__ == '__main__':
src_dir = os.path.dirname(os.path.abspath(__file__)) # 获取当前绝对路径,也可以写死
#src_dir =r"C:\code_nxp\mcu-sdk-2.0_ear2_dev1\middleware\wifi_nxp"
#src_dir =r"C:\code_nxp\wifi_nxp_pan2"
print(src_dir)
files = get_file_list(src_dir)
old_str="#include"
new_str="#include "
pattern = old_str
old_str1="#define"
new_str1="#define "
pattern1 = old_str1
for file in files:
print("file: " + str(file))
with open(file, encoding='utf-8',errors='ignore') as f:
#with open(file,"r") as f:
lines = f.readlines()
ss = ""
for line in lines:
if (re.match(pattern, line)):
#print("line: " + str(line))
line = line.replace(old_str, new_str)
elif (re.match(pattern1, line)):
#print("line: " + str(line))
line = line.replace(old_str1, new_str1)
ss += line
with open(file, "w", encoding='utf-8') as f:
f.write(ss)