Python在文件夹中获取第二个最新文件

时间:2017-06-09 18:10:46

标签: python python-2.7

我正在尝试在目录中获取最新和第二个最新文件。 这是我的代码

{'type': 'fruit', 'name': 'apple', 'fruit_quantity': 20},
{'type': 'vegetable', 'name': 'brocolli','vegetable_quantity': 15},
{'type': 'fruit', 'name': 'banana','fruit_quantity': 10},
{'type': 'fruit', 'name': 'cantaloupe','fruit_quantity': 5}

参考:python second newest file

latest_file [-1]返回最新的文件(" 170608_191655__Equity_Watched.csv"),但latest_file [-2]给了我一个" 170607_082445__Equity_Watched.csv"这不是第二个最近的。我期待得到" 170607_231353__Equity_Watched.csv"

enter image description here

知道我做错了什么吗?谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

看起来您确实需要getmtime,而不是getctime(因为您向我们展示了显示修改次数的屏幕截图)。

答案 1 :(得分:1)

嗯,这里有几种可行的方法。

  1. 反转排序。按另一个方向对其进行排序,然后尝试访问sorted_list[0]sorted_list[1]。也许这会给你一个更有希望的结果
  2. 访问列表中的文件并自行排序。您可以遍历列表,在其上运行os.path.getctime,并使用该数据自行查找最近和最近的第二项。
  3. 继续谷歌或等待另一个答案。或者像Stefan提到的那样使用getmtime ......
  4. 祝你好运!

答案 2 :(得分:1)

sorted_files = sorted(list_of_files, key=os.path.getmtime)
print sorted_files[-2]
相关问题