2013-02-07 25 views
1

我是蟒蛇福利局所以請溫柔..蟒蛇有水珠的回報只有5最新的文件相匹配

我使用水珠收集匹配特定模式的文件列表

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個文件(通過timestap或操作系統報告的創建時間)

/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 修改說明如何從水珠輸出不按默認值

+2

看到這個答案通過時間戳來列出文件的順序: http://stackoverflow.com/a/4500607/665869 – mitnk

回答

3

使用列表切片:

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 
+0

謝謝我會測試這一點,我認爲它需要一個:關閉後](我得到了一個錯誤沒有它) – ReggieS2422

+0

哦,是的,它確實需要一個冒號來打開'爲範圍。 –

+0

我只是測試它並更新了問題,glob不會對輸出進行排序。對不起,因爲我的例子顯示 – ReggieS2422

1

切片輸出排序:

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

我我不確定glob的輸出是否保證排序。

+0

這應該給所有*除了最後五個。 '-5'應該在我的答案中出現在':'之前。 –

+0

@KyleStrand:謝謝,修正。 – Blender

+0

雖然,不確定是否對glob進行排序的好處。 –