Bill
Bill

Reputation: 525

python prints folders and sub folders when only folders needed in python

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

Answers (4)

Błotosmętek
Błotosmętek

Reputation: 12927

(root, dirs, files) = next(os.walk(path))
for name in dirs:

or alternatively use os.listdir

Upvotes: 1

cs95
cs95

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

dhke
dhke

Reputation: 15388

As per the documentation of os.walk():

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; [...]

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

Anthon
Anthon

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

Related Questions