Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python让glob只返回5个最新的文件匹配项_Python_Linux_Glob - Fatal编程技术网

python让glob只返回5个最新的文件匹配项

python让glob只返回5个最新的文件匹配项,python,linux,glob,Python,Linux,Glob,我是蟒蛇新手,所以请温柔点 我使用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 /h

我是蟒蛇新手,所以请温柔点

我使用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个文件(通过timestap或os报告的创建时间)

我该如何做到这一点呢?(是否对列表进行排序,然后只包含最新的5个文件?)

更新 修改以显示默认情况下glob的输出如何不排序

切片输出:

glob.glob('/home/myfiles/*_customer_records_2323_*.zip')[-5:]
我不确定是否保证对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

这应该是除了最后五个之外的所有。
-5
应该在
之前,就像我的回答一样。@KyleStrand:谢谢,修正了。关于不确定
glob
是否对其输出排序,这一点很好。我只是测试了它并更新了问题,glob不对输出排序。很抱歉我的例子中的误导谢谢我要测试一下,我认为它还需要一个:在关闭之后(我没有它就出现了一个错误)哦,是的,它确实需要一个冒号来打开范围的
。我刚刚测试了它并更新了问题,glob没有对输出进行排序。很抱歉,我的例子表明,Edmitnk对您最初问题的评论是一个很好的观点。按时间戳排序可能比按字母排序可靠得多,这是默认情况下
排序的
所做的(尽管您可以使用
参数按您想要的方式进行排序)。请参阅此答案以按时间戳顺序列出文件:
for name in sorted(glob.glob('/home/myfiles/*_customer_records_2323_*.zip'))[-5:]:
    print '\t', name