2

我是蟒蛇新手所以请温柔..

我正在使用 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 个文件?)

UPDATE 修改以显示默认情况下不排序 glob 的输出

4

2 回答 2

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
于 2013-02-07T02:33:13.730 回答
1

切片输出:

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

我不确定是否glob保证对 ' 的输出进行排序。

于 2013-02-07T02:33:08.443 回答