【问题标题】:How to read all new files of a directory with python?如何使用python读取目录的所有新文件?
【发布时间】:2018-06-13 19:14:52
【问题描述】:

我是 Python 的初学者,我想知道如何在此代码中添加条件以仅读取 .../data/ 目录的所有新文件(例如从 24 小时前开始)或(从上次执行时间开始) )。因为我每天都会解析我的.xml 文件,它又会重新解析所有旧文件,这需要时间。

from lxml import etree as ET
import glob
import sys
import os

path = '/home/sky/data/'

for filename in glob.glob(os.path.join(path, '*.xml')):
    try:
        tree = ET.parse(filename)
        root = tree.getroot()

        #other codes here

    except Exception:
        pass

谢谢!

【问题讨论】:

  • 更好的技术是在处理完文件后简单地移动文件。例如,将文件传送到.../incoming/,然后在处理完它们后将它们移动到.../data。这样,您的脚本就可以使用它在 .../incoming 中找到的任何内容。

标签: python xml operating-system lxml glob


【解决方案1】:
for filename in glob.glob(os.path.join(path, '*.xml')):
    if os.path.getmtime(filename) < time.time() - 24 * 60 * 60:  # 24h ago
        continue  # skip the old file
    ...

【讨论】:

  • 次要优化/陷阱(取决于程序的运行时间/被遍历的文件数):time.time() 每次循环都会被调用,因此截止时间将不断变化.如果该程序在许多文件上运行很长时间,这可能会导致意外输出,并且通过重新执行该计算也会导致效率低下(尽管并非不合理)。建议在循环之外提取time.time() - 24 * 60 * 60
  • @BowlingHawk95 Python 会在编译时自动计算常量值,并缓存结果,因此计算只会发生一次(加载程序时)。我同意截止时间是动态的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 2014-11-10
  • 2019-09-28
  • 2016-10-20
  • 2022-01-18
  • 2015-03-01
  • 1970-01-01
相关资源
最近更新 更多