簡體   English   中英

獲取Linux中最新文件的名稱-PYTHON

[英]get the name of most recent file in linux - PYTHON

我想從python中的特定目錄獲取最新文件的名稱嗎?

我用這個

import os
import glob

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
    print fullpath
    list_of_files = glob.glob(fullpath)  
    if not list_of_files:               
        return None                     
    latest_file = max(list_of_files, key=os.path.getctime)
    _, filename = os.path.split(latest_file)
    return filename


if __name__ == "__main__":
    print get_latest_file('ocr', 'uploads', '*.png')

資源

但是我希望代碼返回最新文件的名稱而不指定文件擴展名。 假設有jpg,jpeg,png,gif

我希望摘要覆蓋所有內容。

有輸入嗎?

在最后一行,您只需檢索擴展名為.png的文件

get_latest_file('ocr', 'uploads', '*.png')

如果要檢索不依賴擴展名的所有文件,則只需刪除代碼中glob.glob(' ')的擴展名規范即可 這將檢索目錄中的所有文件。 如果您仍然需要任何擴展名,但沒關系,您也可以使用glob.glob( 。*) 檢索它們,我認為。

如果您不關心擴展名,則可以執行簡單的os.walk迭代。 您可以根據需要將其擴展為過濾擴展。

import os

all_files = {}
root = 'C:\workspace\werkzeug-master'
for r, d, files in os.walk(root):
    for f in files:
        fp = os.path.join(root, r, f)
        all_files[os.path.getmtime(fp)] = fp
keys = all_files.keys()
keys.sort(reverse = True)
print all_files[keys[0]]    

暫無
暫無

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

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