【问题标题】:Glob search files in date order?Glob按日期顺序搜索文件?
【发布时间】:2014-06-19 06:30:22
【问题描述】:

我的 python 脚本中有这行代码。它在特定目录中的所有文件中搜索 *cycle *.log。

for searchedfile in glob.glob("*cycle*.log"):

这非常有效,但是当我将脚本运行到网络位置时,它不会按顺序搜索它们,而是随机搜索。

有没有办法强制代码按日期顺序搜索?

这个问题已经被问到 php 但我不确定它们的区别。

谢谢

【问题讨论】:

标签: python date search glob


【解决方案1】:

使用全局编号。现在,当您使用它时,glob 正在将所有文件同时存储在代码中,并且没有组织这些文件的方法。如果只有最终结果很重要,您可以使用第二个循环来检查文件的日期并以此为基础。如果解析顺序很重要,glob 可能不是最好的方法。

【讨论】:

  • “glob 在代码中同时存储所有文件”什么?
  • @luk32 glob.glob() 代码将整个目录的文件集加载到某种数据结构中。我说代码是因为我不知道他们使用的是列表还是内部数组。
  • 仍然不是代码。也无所谓。问题是,它是任意顺序的,因为它直接从系统中获取。这取决于内核和文件系统驱动程序的实现。
【解决方案2】:

嗯。答案是否定的。 glob 使用 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

【讨论】:

    【解决方案3】:

    您可以使用os.path.getmtimeos.path.getctime 对返回的文件列表进行排序。查看其他 SO answer 并注意 cmets。

    【讨论】:

      【解决方案4】:

      按日期排序文件:

      import glob
      import os
      
      files = glob.glob("*cycle*.log")
      files.sort(key=os.path.getmtime)
      print("\n".join(files))
      

      另见Sorting HOW TO

      【讨论】:

      • 这很好,只需稍作调整即可满足我的需求。 key= 是干什么用的?
      • 啊!不错的一个:)
      【解决方案5】:

      与@jfs 基本相同,但在一行中使用sorted

      import os,glob
      searchedfiles = sorted(glob.glob("*cycle*.log"), key=os.path.getmtime)
      

      【讨论】:

        【解决方案6】:

        如果您的路径是可排序的,那么您始终可以将它们排序为字符串(正如其他人在他们的答案中已经提到的那样)。

        但是,如果您的路径使用像 %d.%m.%Y 这样的日期时间格式,它就会变得更加复杂。由于strptime 不支持通配符,我们开发了一个模块datetime-glob 来解析包含通配符的路径中的日期/时间。

        使用datetime-glob,您可以遍历树、列出目录、解析日期/时间并将它们排序为元组(date/time, path)

        来自模块的测试用例:

        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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多