Python:按日期时间对文件进行更详细的排序 [英] Python: sort files by datetime in more details
问题描述
我在 ubuntu 中使用 python 2.7.我如何以更详细的顺序对文件进行排序,因为我有一个脚本可以在几秒钟内创建 txt 苍蝇的数量.我有一个脚本,它可以找到最旧和最年轻的文件,但它似乎只是与第二个而不是毫秒进行比较.
I using python 2.7 in ubuntu. How do i sort files in more detail order because i had a script that create into numbers of txt flies for split seconds. I had mod a script, it can find the oldest and youngest file but it seem like it just compare with the second but not milliseconds.
我的打印输出:
output_04.txt 06/08/12 12:00:18
output_05.txt 06/08/12 12:00:18
-----------
oldest: output_05.txt
youngest: output_05.txt
-----------
但最旧文件的正确顺序应该是output_04.txt".有高手知道吗?谢谢!
But the right order of oldest file should be "output_04.txt". Any expertise know? Thanks!
更新:谢谢大家.我确实尝试了所有代码,但似乎无法获得我需要的输出.对不起,伙计们,我确实感谢你们.但是我上面的文件的例子有相同的时间,所以如果完整日期,小时,分钟,秒都相同,则必须以毫秒为单位进行比较.不是吗?如我错了请纠正我.谢谢大家!干杯!
Updated: Thanks everyone. I did try out with all of the codes but seem like can't have the output i need. Sorry guys, i did appreciated you all. But the example of my files like above have the same time, so if the full-date, hour, min, sec are all the same, it have to compare by millisecond. isn't it? Correct me if im wrong. Thanks everyone! Cheers!
推荐答案
可以使用os.path.getmtime(path_to_file)
获取文件的修改时间.
You can use os.path.getmtime(path_to_file)
to get the modification time of the file.
对文件列表进行排序的一种方法是使用 os.listdir
创建它们的列表,并获取每个文件的修改时间.您将有一个元组列表,您可以按元组的第二个元素(即修改时间)对其进行排序.
One way of ordering the list of files is to create a list of them with os.listdir
and get the modification time of each one. You would have a list of tuples and you could order it by the second element of the tuple (which would be the modification time).
您也可以使用os.stat_float_times()
检查os.path.getmtime
的分辨率.如果后者返回 True,则 os.path.getmtime
返回一个浮点数(这表明您的分辨率大于秒).
You also can check the resolution of os.path.getmtime
with os.stat_float_times()
. If the latter returns True then os.path.getmtime
returns a float (this indicates you have more resolution than seconds).
这篇关于Python:按日期时间对文件进行更详细的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!