【问题标题】:python have glob return only the 5 most recent file matchespython有glob只返回5个最近的文件匹配
【发布时间】:2013-01-22 10:43:38
【问题描述】:

我是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 的输出的方式

【问题讨论】:

标签: python linux glob


【解决方案1】:

使用列表切片:

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

【讨论】:

  • 谢谢,我会测试一下,我认为它还需要一个:关闭后](没有它我得到一个错误)
  • 哦,是的,它确实需要一个冒号来打开for 范围。
  • 我刚刚对其进行了测试并更新了问题,glob 不会对输出进行排序。对不起,我的例子显示的误导
  • mitnk 对您原始问题的评论是一个很好的观点。按时间戳排序可能比按字母排序更可靠,这是sorted 默认所做的(尽管您可以使用key 参数进行排序)。
【解决方案2】:

切片输出:

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

我不确定glob的输出是否保证排序。

【讨论】:

  • 这应该给所有除了最后五个。 -5 应该在 : 之前,就像我的回答一样。
  • @KyleStrand:谢谢,已修复。
  • 虽然不确定glob 是否对其输出进行排序,但很好。
  • 我刚刚对其进行了测试并更新了问题,glob 不会对输出进行排序。对不起,我的例子显示的误导
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
相关资源
最近更新 更多