2

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?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Bill
  • 515
  • 1
  • 4
  • 15

4 Answers4

2

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).

Anthon
  • 69,918
  • 32
  • 186
  • 246
1
(root, dirs, files) = next(os.walk(path))
for name in dirs:

or alternatively use os.listdir

Błotosmętek
  • 12,717
  • 19
  • 29
1

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[:]
dhke
  • 15,008
  • 2
  • 39
  • 56
1

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.

cs95
  • 379,657
  • 97
  • 704
  • 746