仅在目录,子目录

时间:2017-07-19 01:23:46

标签: 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(folder, filename), 'r+')

1 个答案:

答案 0 :(得分:0)

您可以使用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)上获取实际创建日期有点棘手。