搜索多个文件夹下的excel文件,将含有关键字单元格所在行返回形成新文件

比如我需要获取这两个文件中excel含有关键字的行,文件名就是关键字的值

def find_key_return_row():
    dir = r'C:\Users\admin\Desktop\input_data\work\分多个文件夹,返回匹配上文件名的单元格所在行'
    key_row_list = []
    for root,dirs,files in os.walk(dir):
        for file in files:
            if file.endswith('.xlsx'):
                keyword = file.replace('.xlsx','')
                exc_tmp = pd.read_excel(os.path.join(root,file))
                for index,row in exc_tmp.iterrows():
                    for cell in row:
                        if keyword in str(cell): #excel中有空值和数字,专为str防止报错
                            row['关键字'] = keyword  #增加关键字列
                            key_row_list.append(row)
                            break  #预想的效果是一行中匹配到一个就跳过这一行,不再比对后面的单元格数据
    new_df = pd.DataFrame(data=key_row_list)
    new_df.drop_duplicates(inplace=True)
    new_df.to_excel(r'C:\Users\admin\Desktop\input_data\work\分多个文件夹,返回匹配上文件名的单元格所在行\结果数据.xlsx',index= False)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值