2017-04-06 69 views
0

当我们处理重复的任务时,例如你有一个每周进程得到一个相同的格式,但不同的数字的Excel文件。我们如何让Python只读取文件夹中最近添加或修改的文件(假设文件夹用于保存所有历史文件)?Python - 阅读最近添加或修改的excel文件

当然,我们可以指定一个excel文件名,并使用熊猫或其他库来读取它。但由于我不需要导入以前的文件,而且我也不想打开.py文件来更新excel文件名,所以我希望找到一种自动执行此过程的方法。

+0

你到目前为止尝试过什么?例如,'os'模块提供了多种查询文件夹和文件的工具。 – asongtoruin

+2

[如何在Python中获取文件创建和修改日期/时间?](http://stackoverflow.com/q/237079/953482)可能对您有用。 – Kevin

+0

[如何在Python中获取文件创建和修改日期/时间?](http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-蟒蛇) – waterproof

回答

0

使用os.path.getmtime阅读文件的修改时间。

import os                 
import glob    

excel_folder = 'C:/Users/ThisOne/ExcelStuff/' 

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

mod_dates = [os.path.getmtime(f) for f in excel_files] 

# sort by mod_dates. 
file_date = zip(excel_files, mod_dates).sort(key=lambda d: d[1]) 

newest_file_path = file_date[0][1] 

对类似问题here的回复很好。