Python 仅在目录、子目录中读取过去2个月的文件

Python 仅在目录、子目录中读取过去2个月的文件,python,windows,Python,Windows,我在一个文件夹和子文件夹中有超过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(fol

我在一个文件夹和子文件夹中有超过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+')
您可以使用获取文件的时间戳,然后将其与过去两个月的日期进行比较,即:

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)上获取实际创建日期有点棘手