簡體   English   中英

從文件夾 PYTHON 讀取最新的 excel 文件

[英]Read most recent excel file from folder PYTHON

我有多個 .xlsx 文件放在一個文件夾中。 如何在 PYTHON 中讀取具有今天日期(修改日期)的最新文件? 並將文件名進一步存儲在變量中。

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
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])

不確定您使用的是什么操作系統,但我有適用於 Linux/Raspberry Pi 的解決方案。 也許只需要稍微修改一下,這個方案就可以在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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM