我正在遍历一个巨大的目录,但由于它包含超过 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/