首页 > 解决方案 > 如何使用python读取目录的所有新文件?

问题描述

我是 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

谢谢!

标签: pythonxmloperating-systemlxmlglob

解决方案


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
    ...

推荐阅读