簡體   English   中英

python have glob只返回最近的5個文件匹配項

[英]python have glob return only the 5 most recent file matches

我是python newb,所以請保持溫柔。

我正在使用glob收集與特定模式匹配的文件列表

for name in glob.glob('/home/myfiles/*_customer_records_2323_*.zip')
print '\t', name

輸出是這樣的

/home/myfiles/20130110_customer_records_2323_something.zip
/home/myfiles/20130102_customer_records_2323_something.zip
/home/myfiles/20130101_customer_records_2323_something.zip
/home/myfiles/20130103_customer_records_2323_something.zip
/home/myfiles/20130104_customer_records_2323_something.zip
/home/myfiles/20130105_customer_records_2323_something.zip
/home/myfiles/20130107_customer_records_2323_something.zip
/home/myfiles/20130106_customer_records_2323_something.zip

但是我希望輸出僅是最新的5個文件(通過時間戳或os報告的創建時間)

/home/myfiles/20130106_customer_records_2323_something.zip
/home/myfiles/20130107_customer_records_2323_something.zip
/home/myfiles/20130108_customer_records_2323_something.zip
/home/myfiles/20130109_customer_records_2323_something.zip
/home/myfiles/20130110_customer_records_2323_something.zip

關於如何實現此目標的想法? (列表是否已排序,然后僅包含最新的5個文件?)

UPDATE修改為顯示默認情況下如何不對glob的輸出排序

使用列表切片:

for name in glob.glob('/home/myfiles/*_customer_records_2323_*.zip')[-5:]:
    print '\t', name

編輯:如果glob不會自動對輸出進行排序,請嘗試以下操作:

for name in sorted(glob.glob('/home/myfiles/*_customer_records_2323_*.zip'))[-5:]:
    print '\t', name

切片輸出:

glob.glob('/home/myfiles/*_customer_records_2323_*.zip')[-5:]

我不確定glob的輸出是否可以排序。

暫無
暫無

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

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