如何在有一些先决条件的情况下从一个位置读取excel文件


  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的日期部分不是固定的,它是系统的当前日期。如何在运行程序时每天自动更改文件名中的日期部分?

期待您对的支持

  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'