【问题标题】:How to import a file from a folder where the ending characters can change - python pandas?如何从结尾字符可以更改的文件夹中导入文件-python pandas?
【发布时间】:2019-08-26 13:51:34
【问题描述】:

我目前有一个文件夹,其中包含我试图从中读取的多个名称相似的文件。 例如: 文件夹包含文件:

apple_2019_08_26_23434.xls
apple_2019_08_25_55345.xls
apple_2019_08_24_99345.xls

文件的名称格式很简单:

 apple_<date>_<5 random numbers>.xls

如果我不关心末尾的随机 5 位数字,如何将 excel 文件读入 pandas df?

例如

df = pd.read_excel('e:\Document\apple_2019_08_26_<***wildcard***>.xls')

谢谢!

【问题讨论】:

标签: python pandas wildcard


【解决方案1】:

您可以通过 glob 使用 unix 风格的路径名扩展。

import glob

# get .txt files in current directory
txt_files = glob.glob('./*.txt')

# get .xls files in some_dir
xls_files = glob.glob('some_dir/*.xls')

# do stuff with files
# ...

在这里,* 基本上意味着“任何东西”。

以熊猫为例:

import glob

for xls_file in glob.glob('e:/Document/apple_2019_08_26_*.xls'):
    df = pd.read_excel(xls_file)

    # do stuff with df
    # ...

【讨论】:

    【解决方案2】:

    使用os.chdir 更改您的目录,然后导入startwith 正确名称的所有文件:

    import os
    os.chdir(r'e:\Document')
    dfs = [pd.read_excel(file) for file in os.listdir() if file.startswith('apple_2019_08')]
    

    现在您可以通过索引访问每个数据帧:

    print(dfs[0])
    
    print(dfs[1])
    

    如果格式相同,则将它们组合成一个大数据框

    df_all = pd.concat(dfs, ignore_index=True)
    

    【讨论】:

      【解决方案3】:

      如果您希望代码中的 5 位部分可以更改,您可以尝试以下操作:

      from os import listdir
      from os.path import isfile, join
      import pandas as pd
      
      mypath = '/Users/username/aPath'
      onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
      
      fiveDigitNumber = onlyfiles[0][17:22]
      filename = onlyfiles[0][:17]+fiveDigitNumber+onlyfiles[0][22:]
      
      df = pd.read_excel(filename)
      

      【讨论】:

        猜你喜欢
        • 2014-09-30
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        相关资源
        最近更新 更多