Reputation: 195
I have 100+ folders in the directory of Results. within each folders consist of 100+ images
I want to extract the list of folders that were modified since the last 10 days
i have use the below code to write but it returned the images files name with their respective modification date. i do not want the files but only want the folders that contain. anyone can help to see whats wrong with my code
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))
Upvotes: 0
Views: 235
Reputation: 105
You are iterating over, and printing the modification time for the files, not folders.
To get the folders modification time, change the line:
for fname in files:
To
for fname in dirs:
If you want the latest modification time based only on the files in a folder, see the code below. (A folder's modification date is changed to 'now' when you copy a file into it, even if the file's modification time is really old.)
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))
Upvotes: 1