【问题标题】:How read excel from folder without specify excel name?如何在不指定 excel 名称的情况下从文件夹中读取 excel?
【发布时间】:2019-06-03 07:50:12
【问题描述】:

我想从文件夹中读取_excel并加载到数据库中,但是excel每周都会刷新并更改名称(ReportWK01,ReportWK02,...)在那个文件夹中(名称To_Load)只是我需要的一个excel。

我尝试指定路径,然后 read_excel,但我不知道正确的语法。

path = rb'\\csd-file\dd\bb\ss\uu\To_Load'
results = os.path.join(path, rb"*\*.xlsx")
df = pd.read_excel(results, engine='python')

写给我

ValueError: Must explicitly set engine if not passing in buffer or path for io.

【问题讨论】:

标签: python excel pandas path


【解决方案1】:
## can you try reading it based on most recent time stamp
import os                                                                   
import glob             

folder_path ='\\csd-file\dd\bb\ss\uu\To_Load'

# glob.glob returns all paths matching the pattern.
excel_files = list(glob.glob(os.path.join(folder_path, '*.xls*')))

mod_dates = [os.path.getmtime(f) for f in excel_files]
print(mod_dates)
# sort by mod_dates.
file_date = sorted(zip(excel_files, mod_dates),reverse=True)
print("*"*100)
print(file_date)
newest_file_path = file_date[0][0]
df = pd.read_excel(newest_file_path)

【讨论】:

  • vrana95 它写给我 TypeError: Can't mix strings and bytes in path components
  • 您能否尝试在 folder_path 中给出确切的文件夹路径。我有更新代码
  • 'zip' 对象没有属性 'sort' 所以我尝试了file_date = zip(excel_files, mod_dates) file_date=sorted(file_date, key=lambda d: d[1]) 它写给我 IndexError: list index out of range
  • 我只在 path 和 excel_files = list(glob.glob(os.path.join(folder_path, r'*.xls*'))) 之前添加了 r 并且它有效。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2014-12-26
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
相关资源
最近更新 更多