How to read all new files of a directory with python?

我的未来我决定 提交于 2019-12-02 18:37:02

问题


I'm beginner in Python and I'm wondering to know how can I add a condition in this code to read only all new files of .../data/ directory (for example from 24 hours ago) or (from last execution time). Because I parse my .xml files every day and it is parsing all old files again and it takes time.

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

Thanks!


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


来源:https://stackoverflow.com/questions/50844668/how-to-read-all-new-files-of-a-directory-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!