What is the Python way to walk a directory tree?

后端 未结 11 1668
走了就别回头了
走了就别回头了 2020-12-06 09:52

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I\'m using Python 3.2

from os import *
from os.pat         


        
11条回答
  •  忘掉有多难
    2020-12-06 10:03

    While googling for the same info, I found this question.

    I am posting here the smallest, clearest code which I found at http://www.pythoncentral.io/how-to-traverse-a-directory-tree-in-python-guide-to-os-walk/ (rather than just posting the URL, in case of link rot).

    The page has some useful info and also points to a few other relevant pages.

    # Import the os module, for the os.walk function
    import os
    
    # Set the directory you want to start from
    rootDir = '.'
    for dirName, subdirList, fileList in os.walk(rootDir):
        print('Found directory: %s' % dirName)
        for fname in fileList:
            print('\t%s' % fname)
    

提交回复
热议问题