python - 如何使用 os.walk 根据修改日期过滤文件夹?

标签 python python-datetime os.walk os.path

我正在遍历一个巨大的目录,但由于它包含超过 500k 个文件,我想根据上次修改日期过滤该函数输入的文件夹。

我只想输入过去 7 天内修改过的文件夹。

这是我到目前为止的代码:

def checkFolderFileTimestamps(rootFolder):
    
    for root, dirs, files in os.walk(rootFolder):
            print(datetime.fromtimestamp(os.path.getmtime(os.path.join(root))).strftime("%Y:%m:%d"))
            
            for file in files:
          
                if file.endswith(".png") and datetime.fromtimestamp(os.path.getmtime(os.path.join(root, file))).strftime("%Y:%m:%d") > datetime.now().strftime("2021:5:1"):
                    print(os.path.join(root, file))
                    print(datetime.fromtimestamp(os.path.getmtime(os.path.join(root, file))).strftime("%Y:%m:%d") == datetime.now().strftime("%Y:%m:%d"))

                    imageArray.append(os.path.join(root, file))
                    imageName.append(file)
                    print(imageArray)

最佳答案

将根文件夹放入os.walk()中。您可以根据您的需求调整path.endswith()

import os
import datetime as dt

now = dt.datetime.now()
ago = now-dt.timedelta(days=7)

modified=[]

for root, dirs,files in os.walk('C:/Users/raghavg/heads/LiveProjects/'):  
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)    
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago and path.endswith((".pdf",".png")):
            modified.append(path)
                
print(modified)

modified 应该包含您上周更新的文件的所有路径

关于python - 如何使用 os.walk 根据修改日期过滤文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67530215/

相关文章:

python - C++/Python 中对象和结构的二进制文件结构

python - 是否有一个对象比任何有效的 datetime.datetime(...) 都小?

python - datetime.fromisoformat 的文档示例引发无效的 isoformat 字符串错误

Python从字符串中识别时间戳格式

python - os.walk 在第一次找到后停止寻找子目录

python - 机器学习算法中的示例顺序 (Scikit Learn)

python - 是否可以在python中的@property setter中设置其他属性

python - 使用 os.walk() 时文件名随机损坏

Python:无法访问通过多处理更改的内存

python - 需要使用 os.walk() 的特定文件的路径