【问题标题】:Automatically search folder for specific excel file and import into pandas自动搜索特定 excel 文件的文件夹并导入 pandas
【发布时间】:2020-01-31 06:42:51
【问题描述】:

到目前为止,我还没有看到我要问什么。

我在 C 盘上名为 RedRose 的文件夹中有 2 个 excel 文件。 这些文件以日期 09-30-2019_rest_of_name1, ...name2 开头。 _rest_of_name1, ...name2 是静态的,只有日期会每天更新,因为每天都会将新文件添加到 RedRose 文件夹中。

在运行命令上使用 Python 我想自动查看该文件夹,搜索每个文件名并将每个文件导入到它自己的 pandas 数据框中。

想一想,这可以用 Python 完成吗?

不知道从哪里开始

【问题讨论】:

    标签: python excel pandas import directory


    【解决方案1】:

    您可以使用glob 模块获取当前目录中的文件列表。

    import glob
    files = glob.glob('C:\RedRose\*.xls*')
    

    它返回一个扩展名为.xls 类型的文件列表,并使用正则表达式来检查名称是否正确。此外,Windows 路径格式可能不同

    使用 Pandas 库中的 read_excel 函数将 excel 文件读入 DataFrame。您可以遍历 files 中的所有文件名,并将每个 DataFrame 存储为列表或字典的元素。

    import pandas as pd
    
    dataframes = []
    for filename in files:
        dataframes.append(pd.read_excel(filename))
    

    要读入字典,您需要为每个 DataFrame 指定一个键。我建议使用文件名作为键,因为它是唯一的。

    【讨论】:

    • Harish 谢谢!!!我会试一试。您能否扩展字典部分的代码。我希望有 2 个 diff 数据帧,每个数据帧彼此独立,每天都有不同的数据帧,基于每日输入文件。
    • 对于字典,您可以执行 dataframes[filename] = pd.read_excel(filename) 之类的操作,然后使用文件名作为键访问您想要的 DataFrame。
    • 哈里什,谢谢。您的指导帮助我使代码正常工作。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多