我在一个文件夹中放置了多个.xlsx文件。我如何在PYTHON中读取具有今天日期(修改日期)的最新文件?并进一步将文件名存储在一个变量中。
from pathlib import Path
# Save all .xlsx files paths and modification time into paths
paths = [(p.stat().st_mtime, p) for p in Path("path/to/folder").iterdir() if p.suffix == ".xlsx"]
# Sort them by the modification time
paths = sorted(paths, key=lambda x: x[0], reverse=True)
# Get the last modified file
last = paths[0][1]
注意last
的类型为Path。如果你想要一个字符串,你可以把最后一行改成
last = str(paths[0][1])
import os
# list all .xlsx files in absolute directory
files = (os.path.abspath(file) for file in os.listdir('/path/to/PYTHON') if file.endswith('.xlsx'))
# get their last updated time
files_and_updated_time = ((file, os.path.getmtime(file)) for file in files)
# sort out the lastest updated xlsx
last_updated_xlsx = sorted(files_and_updated_time, key=lambda x: x[1], reverse=True)
# check if this said xlsx exists
# if so, store its absolute path in `result`
if last_updated_xlsx:
result = last_updated_xlsx[0][0]
else:
result = None
不知道你在什么操作系统上,但我有Linux/树莓派的解决方案。也许只有一点需要修改这个解决方案在Windows上实现。
导入库:
- 使用
datetime
库获取今天的日期。 - 在指定目录或文件夹中查找文件,使用
os
库。
现在,对于编码部分:
import os
from datetime import datetime
# This gets today's date in string with the format of 2021-12-31.
today = datetime.today().strftime('%Y-%m-%d')
# Assume your filename is only today's date and the extension at the end.
path = '/home/pi/' + today + '.xlsx'
# If there's a same filename found in this path.
if os.path.exists(path):
print("File found")
# Gets the filename from the path and store it in the 'filename' variable.
filename = os.path.basename('/home/pi/' + path + '.xlsx')
else:
print("File not found")