简体   繁体   中英

python have glob return only the 5 most recent file matches

I'm a python newb so please be gentle..

I'm using glob to gather a list of files that match a specific pattern

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

The output is then something like

/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

But I would like the output to be only the newest 5 files only (via the timestap or the os reported creation time)

/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

And Idea on how I can accomplish this? (have the list be sorted and then contain only the newest 5 files?)

UPDATE Modified to show how output from glob is NOT sorted by default

Use list-slicing:

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

EDIT: if glob doesn't automatically sort the output, try the following:

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

Slice the output:

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

I'm not sure if glob 's output is guaranteed to be sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM