我正在遍历一个巨大的目录,但由于它包含超过 50 万个文件,我想根据函数输入的文件夹的上次修改日期过滤它们。
我只想输入过去 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)
答案 0 :(得分:0)
将您的根文件夹放在 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)
修改后应该包含您上周更新的文件的所有路径
答案 1 :(得分:0)
我假设您希望在根文件夹中创建过去 7 天内修改过的文件夹列表。
import datetime
import os
# Date a week ago
week_ago = datetime.date.today() - datetime.timedelta(days=7)
您可以通过简单的比较来检查日期是否小于一周前。
today = datetime.date.today()
print(today > week_ago)
# Output is True
以下代码生成 rootFolder
中过去 7 天内修改过的文件夹列表。
folders = [os.path.join(rootFolder,f.name) for f in os.scandir(rootFolder)
if f.is_dir() and
datetime.date.fromtimestamp(os.path.getmtime(os.path.join(rootFolder,f))) > week_ago]