2017-07-08 3 views
2

Ich mache ein Programm, das alle Ordner über 90 Tage in Python druckt.
Hier ist mein Code:Python druckt Ordner und Unterordner, wenn nur Ordner in Python benötigt

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) 

Das Problem ist, dass diese alle Ordner druckt, aber er druckt auch die Unterverzeichnisse der Ordner, die ich nicht brauche. Wie kann ich den Code ändern, so dass nur die Ordner gedruckt werden?

Antwort

2

brechen kurz nach der Verz Druck:

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 

Oder schauen Sie in os.listdir() verwenden, die nicht in die Unterverzeichnisse nicht Rekursion (aber Sie werden für nicht-Verzeichnisse im Ergebnis überprüfen).

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

oder alternativ os.listdir

+1

Richtig, hier ist 'next' anstelle von Indexierung zu verwenden. –

1

Gemäß der Dokumentation von os.walk() verwenden:

Wenn topdownTrue ist, kann der Anrufer die dirnames Liste an Ort und Stelle ändern (vielleicht mit del oder Slice Zuordnung) und walk() werden nur in Unterverzeichnisse zurückgespielt, deren Namen in dirnames bleiben; [...]

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[:] 
1

ein Beispiel unter Verwendung 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 wird true zurück, wenn eine Datei nur ein Verzeichnis ist.

Verwandte Themen