python在python中只需要文件夹时打印文件夹和子文件夹

时间:2017-07-08 11:43:14

标签: python directory python-os

我正在制作一个程序,在python中打印90天以上的所有文件夹 这是我的代码:

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)

问题是这会打印所有文件夹,但它也会打印文件夹的子文件夹,这是我不需要的。如何更改代码以便仅打印文件夹?

4 个答案:

答案 0 :(得分:2)

打印后暂停:

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

或者考虑使用os.listdir(),它不会递归到子目录中(但是你必须检查结果中的非目录)。

答案 1 :(得分:1)

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

或者使用os.listdir

答案 2 :(得分:1)

根据os.walk()的文档:

  

topdownTrue时,来电者可以就地修改dirnames列表(可能使用del或切片分配),walk()将{}只递归到名称保留在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[:]

答案 3 :(得分:1)

使用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将返回true。