【问题标题】:Finding files in Python with date filter使用日期过滤器在 Python 中查找文件
【发布时间】:2018-08-06 08:16:10
【问题描述】:

如何在不爬取整个搜索目录的情况下,根据比 Python 中的某些查询日期更新的过滤来查找文件?例如,在 Bash/*nix(在 MacOS 上测试)中,我可以执行 find . -newermt '2018-01-17 03:28:46',它快速 搜索仅比指定查询日期更新的文件。在 Python 中我可以做到:

import os
import datetime

query_date = datetime.datetime.fromtimestamp(int(float(1516188526532974000)/1000000000))
results = []
for root, dirs, files in os.walk('/Users/Nafty/Sync/sxs'):
    for filename in files:
        path = os.path.join(root, filename)
        file_mtime = datetime.datetime.fromtimestamp(os.stat(path).st_mtime)
        if(file_mtime > query_date):
            results.append(path)  # yield path?

return results

但是,这需要更长的时间,而且似乎无论如何都要遍历整个目录。

有没有办法在 Python 中进行快速搜索版本的日期过滤目录爬取,类似于 Bash 示例?

【问题讨论】:

标签: python bash directory find subdirectory


【解决方案1】:

您提供的代码似乎是在纯 python 中执行此操作的方法。如果速度对您来说非常重要,您可能需要考虑运行您从 python 代码中提到的 bash 命令,然后解析输出。可以使用以下代码:

import subprocess
timestamp = '"2018-01-17 03:28:46"'
path = '.'
files = []
find = subprocess.Popen('find ' + path + ' -newermt ' + timestamp, shell=True, 
stdout=subprocess.PIPE)
for line in find.stdout:
   files.append(line.decode('UTF-8').strip())
print(files)

【讨论】:

  • 谢谢。顺便说一句,如果遵循这种技术,我会使用-print0 然后使用.split('\0')。仍然想知道 Python 中是否有一种方法可以直接以相同或相似的速度完成。
猜你喜欢
  • 2021-04-07
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
相关资源
最近更新 更多