【问题标题】:How to read excel file from a location with some preconditions?如何从具有一些先决条件的位置读取 excel 文件?
【发布时间】:2020-11-28 13:31:07
【问题描述】:
  1. 我需要读取一个 excel,其中有一些文件夹,每个文件夹在该位置包含许多文件,我想要的文件将在其中一个文件夹中。如何从该位置读取我想要的文件?我的文件名是Daily Report on (18-Nov-2020)_ALL.xlsm,我想读为df1 = pd.read_excel(r'C:\(many folders here)\Daily Report on (18-Nov-2020)_ALL.xlsm',header = 1, usecols = "A:B,D:N,U,W,Z",skiprows = range(1,3))

  2. 我的文件名18-Nov-2020的日期部分不固定,是系统的当前日期。如何每天在运行程序时自动更改文件名中的日期部分?

期待您的支持

【问题讨论】:

    标签: python-3.x excel pandas dataframe


    【解决方案1】:
    1. 使用glob 模块。 '**' 表示“所有可能的目录和子目录”还要确保,recursive=True
    from glob import glob
    import os
    today_file_path = glob(os.path.join(fixed_path, '**', today_filename), recursive=True)[0]
    
    1. 使用日期格式。 %d 是月份中的某天,%b% 是月份的缩写,%Y 是年份
    from datetime import date
    today_formatted = date.today().strftime('%d-%b-%Y')
    today_filename = 'Daily Report on ({})_ALL.xlsm'.format(today_formatted)
    print(today_filename)
    

    输出:

    'Daily Report on (28-Nov-2020)_ALL.xlsm'
    

    【讨论】:

    • 谢谢@Mark。我的第二点解决了。请帮我解决第一点。我不知道预期文件的具体文件夹位置。如何从多个文件夹中读取我想要的文件?
    • 是否有一组固定的文件夹,文件可能出现在哪里?例如,有 3 个不同的文件夹,但您不知道该查看哪个文件夹?
    • 不!文件夹不固定。某些路径是固定的,例如 C:\RPA\2020(许多文件夹不固定)\Daily Report on (28-Nov-2020)_ALL.xlsm @Mark
    • 我编辑了我的答案以包含第一个问题。它对你有用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多