python使用glob仅返回最新的5个文件匹配项

2 投票
2 回答
723 浏览
提问于 2025-04-17 15:02

我刚学Python,所以请多多包涵。

我正在使用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个文件(可以通过时间戳或者操作系统报告的创建时间来判断)。

/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个文件?)

更新:我修改了内容,显示glob的输出默认是没有排序的。

2 个回答

1

切片输出:

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

我不太确定glob的输出结果是否一定是有序的。

4

使用列表切片:

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

撰写回答