读取文件并将文件内的符合条件的行按指定格式写入到excl,这里的场景是读取实体类,并将字段写入到excl中过滤掉其他的注释字段、方法等。
读取文件列表
def get_files_in_folder(folder_path):
file_names = os.listdir(folder_path)
return file_names
完整代码
import re
import os
import openpyxl
file = "D:\\path\\"
def toexcle(workbook,fileName):
with open("D:\\path\\"+fileName, 'r',encoding='utf-8') as file:
_fn = fileName.split("\\")
if len(_fn)>1:
fn = _fn[1]+"_"+_fn[0]
else:
fn = _fn[0]
workbook.create_sheet(fn)
sheet = workbook[fn]
l = []
while True:
line = file.readline()
if not line:
break
if (line.find("private")>0 and line.find("static")<0 and line.find("void")<0) and line.startswith("//")==False and line!="":
# print(line)
l = re.sub(" +"," ",line.strip().replace(";"," ")).split(" ")
print(l)
sheet.append([l[1], l[2], l[3].replace("//","") if len(l)>3 else ""])
def get_files_in_folder(folder_path):
file_names = os.listdir(folder_path)
return file_names
if __name__ == '__main__':
workbook = openpyxl.Workbook()
path = get_files_in_folder(file)
files = []
for p in path:
pp = file+"\\"+p
if os.path.isdir(pp):
ll = get_files_in_folder(pp)
for l in ll:
files.append(p+"\\"+l)
else:
files.append(p)
for ff in files:
toexcle(workbook,ff)
workbook.save("example.xlsx")