Reputation: 525
I am making a program that prints all the folders over 90 days in python.
Here is my code:
import os
from datetime import date
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
old_dirs = []
today = date.today()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to
scan from: ")
path = path.encode('utf-8')
for root, dirs, files in os.walk(path):
for name in dirs:
filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
if (today - filedate).days > 90:
print name
old_dirs.append(name)
The problem is that this prints all folders, but it also prints the sub folders of the folders, which I don't need. How can I change the code so that it only prints the folders?
Upvotes: 2
Views: 71
Reputation: 12927
(root, dirs, files) = next(os.walk(path))
for name in dirs:
or alternatively use os.listdir
Upvotes: 1
Reputation: 402413
An example using os.listdir
:
root = os.getcwd()
for name in os.listdir(path):
full_path = os.path.join(root, name)
if os.path.isdir(full_path):
filedate = date.fromtimestamp(os.path.getmtime(full_path))
if (today - filedate).days > 90:
old_dirs.append(name)
os.path.isdir
will return true if a file is a directory only.
Upvotes: 1
Reputation: 15388
As per the documentation of os.walk()
:
When
topdown
isTrue
, the caller can modify thedirnames
list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain indirnames
; [...]
for root, dirs, files in os.walk(path):
for name in dirs:
filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
if (today - filedate).days > 90:
print name
old_dirs.append(name)
del dirs[:]
Upvotes: 1
Reputation: 76607
Just break after printing the dirs:
for root, dirs, files in os.walk(path):
for name in dirs:
filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
if (today - filedate).days > 90:
print name
old_dirs.append(name)
break
Or look into using os.listdir()
, that doesn't recurse into the subdirectories (but you'll have to check for non-directories in the result).
Upvotes: 2