按日期顺序搜索文件?
我在我的Python脚本里有这么一行代码。它会在特定的文件夹里搜索所有包含“cycle”的日志文件,文件名是以“.log”结尾的。
for searchedfile in glob.glob("*cycle*.log"):
这个功能运行得很好,不过当我把脚本运行到网络位置时,它搜索的顺序就乱了,而不是按顺序搜索。
有没有办法强制代码按日期顺序搜索呢?
这个问题在PHP中也有人问过,但我不太清楚两者之间的区别。
谢谢!
7 个回答
1
如果你的路径是可以排序的顺序,那么你可以像其他人提到的那样,把它们当作字符串来排序。
不过,如果你的路径使用的是像 %d.%m.%Y
这样的日期时间格式,那就稍微复杂一些。因为 strptime
不支持通配符,所以我们开发了一个模块 datetime-glob,可以从包含通配符的路径中解析出日期和时间。
使用 datetime-glob
,你可以遍历文件夹,列出目录,解析出日期和时间,然后把它们按元组 (日期/时间, 路径)
的形式排序。
来自这个模块的测试案例:
import pathlib
import tempfile
import datetime_glob
def test_sort_listdir(self):
with tempfile.TemporaryDirectory() as tempdir:
pth = pathlib.Path(tempdir)
(pth / 'some-description-20.3.2016.txt').write_text('tested')
(pth / 'other-description-7.4.2016.txt').write_text('tested')
(pth / 'yet-another-description-1.1.2016.txt').write_text('tested')
matcher = datetime_glob.Matcher(pattern='*%-d.%-m.%Y.txt')
subpths_matches = [(subpth, matcher.match(subpth.name)) for subpth in pth.iterdir()]
dtimes_subpths = [(mtch.as_datetime(), subpth) for subpth, mtch in subpths_matches]
subpths = [subpth for _, subpth in sorted(dtimes_subpths)]
# yapf: disable
expected = [
pth / 'yet-another-description-1.1.2016.txt',
pth / 'some-description-20.3.2016.txt',
pth / 'other-description-7.4.2016.txt'
]
# yapf: enable
self.assertListEqual(subpths, expected)
2
现在只需要使用pathlib模块就可以做到这一点:
import pathlib
found = pathlib.Path.cwd().glob('*.py')
found = sorted(found,key=lambda file: pathlib.Path(file).lstat().st_mtime)
5
好吧,答案是否定的。glob
这个模块是用 os.listdir
来获取文件列表的,而 os.listdir
的描述是:
"返回一个列表,里面包含指定路径下目录的所有条目的名字。这个列表的顺序是随机的。即使目录里有特殊条目 '.' 和 '..',它们也不会被包含在内。"
所以你其实很幸运,得到了一个排序的结果。你需要自己去排序。
这个方法对我有效:
import glob
import os
import time
searchedfile = glob.glob("*.cpp")
files = sorted( searchedfile, key = lambda file: os.path.getctime(file))
for file in files:
print("{} - {}".format(file, time.ctime(os.path.getctime(file))) )
另外要注意,这里使用的是创建时间,如果你想用修改时间的话,使用的函数应该是 getmtime
。
16
基本上和 @jfs 的意思一样,不过用一行代码实现,使用了 sorted
函数。
import os,glob
searchedfiles = sorted(glob.glob("*cycle*.log"), key=os.path.getmtime)
118
要按日期对文件进行排序:
import glob
import os
files = glob.glob("*cycle*.log")
files.sort(key=os.path.getmtime)
print("\n".join(files))
另外可以参考 排序教程。