python读取文件并写入excl

本文介绍了如何使用Python的openpyxl库读取文件,筛选出符合条件的实体类字段,排除注释,然后将这些数据以指定格式写入到Excel工作簿中。
摘要由CSDN通过智能技术生成

读取文件并将文件内的符合条件的行按指定格式写入到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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆芽脚脚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值