【python】遍历目录下excel表关键字

import os
import pandas as pd

def search_excel_files(directory, keyword):
    found_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.xlsx'):
                file_path = os.path.join(root, file)
                try:
                    # 使用 ExcelFile 对象获取工作表名称列表
                    df = pd.ExcelFile(file_path)
                    sheet_names = df.sheet_names

                    # 遍历工作表名称列表,读取特定工作表
                    for sheet_name in sheet_names:
                        data = pd.read_excel(file_path, sheet_name=sheet_name)
                        if keyword in data.to_string():
                            found_files.append((file_path, sheet_name))  # 以元组形式保存文件路径和工作表名称
                            break
                except Exception as e:
                    print(f"Error reading {file_path}: {e}")
    return found_files

directory = '/path/to/your/directory'  # 将此路径替换为你要搜索的目录
keyword = 'house'
found_files = search_excel_files(directory, keyword)

if found_files:
    print(f"Found the keyword '{keyword}' in the following Excel files:")
    for file, sheet_name in found_files:  # 同时遍历文件路径和工作表名称
        print(f"File: {file}, Sheet: {sheet_name}")  # 打印文件路径和工作表名称
else:
    print(f"No files containing the keyword '{keyword}' were found.")

指定的目录放在数据盘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值