如何使用python读取目录的所有新文件? [英] How to read all new files of a directory with python?

查看:411
本文介绍了如何使用python读取目录的所有新文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

谢谢!

推荐答案

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

这篇关于如何使用python读取目录的所有新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆