繁体   English   中英

仅在目录,子目录中读取最近2个月的文件

[英]Read files for last 2 months only in directory, sub-directories

我在一个文件夹和一个子文件夹中有> 6个​​月的文件,目前我可以打开和读取所有文件并将其写入csv文件,但是,我想打开和读取仅在最近2个月内创建的文件。

这是我用来打开和读取所有文件的代码-

for folder, sub_folders, files in os.walk(dirSelected):
    for filename in files:
        if fnmatch(filename, "*.CST"):
            f = open(os.path.join(folder, filename), 'r+')

您可以使用os.path.getctime()来获取文件的时间戳,然后可以将其与过去两个月的日期进行比较,即:

import datetime
import os

root_dir = "."  # whatever your target directory is
current_date = datetime.datetime.now()  # get our current date and time
past_date = current_date - datetime.timedelta(days=60)
# you can account for month length if needed, this is a 60 days in the past approximation

for folder, sub_folders, files in os.walk(root_dir):
    for filename in files:
        if filename[-4:].lower() == ".cst":  # we're only interested in .cst files
            # get the filename's path relative to the root dir
            target_path = os.path.join(folder, filename)
            # get the file's timestamp:
            c_ts = os.path.getctime(target_path)  # NOTE: this works only on Windows!
            c_date = datetime.datetime.fromtimestamp(c_ts)  # convert it into a datetime
            if c_date >= past_date:  # if created after our past date
                with open(target_path, "r+") as f:
                    # do as you will with the file handle in `f`
                    pass

既然你已经与标记你的问题windows我假设你正在使用Windows -得到实际的创建日期是在其他平台上(特别是Linux)的麻烦一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM