2016-10-12 13 views
0

我想從python中的特定目錄獲取最新文件的名稱?在linux中獲取最新文件的名稱 - 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') 

Source

但我想代碼,而無需指定文件的擴展名的最新文件的名稱恢復。 讓我們來說說如果有jpg,jpeg,png,gif

我想要這些代碼片段來覆蓋它們。

任何輸入?

+1

與glob.glob你也可以替換文件結尾後綴。你試過了:print get_latest_file('ocr','uploads','*') – hasan

+0

@hasan這就是答案。你想更清楚地寫下來嗎? – bbastu

回答

2

與最後一行你只是檢索與如果你想獲取不依賴於擴展名的文件擴展名png格式

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

的文件,你只需要刪除您的擴展規範的代碼glob的。 glob('')。這將檢索您的目錄中的所有文件。如果你仍然需要任何擴展名,但是不用擔心你可以用glob.glob檢索它們(。*),我想。

0

如果你不關心擴展,一個簡單的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]]