我在结果目录中有100多个文件夹。每个文件夹中包含100多张图片
我想提取自过去10天以来修改过的文件夹列表
我使用下面的代码编写,但它返回了图像文件名及其各自的修改日期。我不想要文件但只想要包含的文件夹。任何人都可以帮我看看我的代码有什么问题
import os
import datetime as dt
now = dt.datetime.now()
ago = now-dt.timedelta(minutes=14400) # 14400 minutes = 10 days
for root, dirs,folders in os.walk('/Results/'):
for fname in folders:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime)
if mtime > ago:
print('%s ; %s'%(path,mtime))
答案 0 :(得分:1)
您正在迭代,并打印文件的修改时间,而不是文件夹。
要获取文件夹修改时间,请更改以下行:
for fname in files:
要
for fname in dirs:
如果您希望最新修改时间仅基于文件夹中的文件,请参阅下面的代码。 (当您将文件复制到文件夹时,文件夹的修改日期会更改为“现在”,即使文件的修改时间非常旧。)
import os
import datetime as dt
now = dt.datetime.now()
ago = now-dt.timedelta(minutes=14400) # 14400 minutes = 10 days
# Get the folder's modification time first
results = {} # stores a dictionary of folders with their latest file modification date. (Giving the folder's modification date)
for root, dirs, files in os.walk('/Results/'): # RENAMED folders TO files
for fname in files:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime)
folder = os.path.dirname(path) # Get the folder name.
if folder not in results or results[folder] > mtime: # set the folder's modification date to the file's; only if the folder does not exist in the results list or if the file's modification time is less than that stored as the folder's.
results[folder] = mtime
# Now, print all the folders whose modification date is less than 10 days.
for path, mtime in results.items()
if mtime > ago:
print('%s ; %s'%(path, mtime))