简体   繁体   中英

How can I get all filename in different directories?

Lets say the directories hierarchy looks like this:

          A(root)
          |
B---------C--------D
|         |        |
fileB.h  fileC.png  fileD.py
         fileC1.jpg
          E
          |
         fileE.py

How can I access all the doc? Or just get the path. Is there a way to iterlate all?

What I do:

path = sys.path[0]
for filename_dir in os.listdir(path):
     filename, ext = os.path.splitext(filename_dir)
     if ext == '.h':
         #do something
     elif ext == '.png'
         #do something
     .....

But as I know listdir can only access the directory where my program's py file located.

This gives only the dirs and files under a directory, but not recursively:

import os

for filename in os.listdir(path):
    print filename

If you want to list absolute paths:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

If you want resursive search, this gives you an iterator that returns 3-tuples including the parent directory, list of directories, and list of files at each iteration:

for i,j,k in os.walk('.'):
    print i, j, k

For example:

    import os

    path = sys.path[0]

    for dirname, dirnames, filenames in os.walk(path):
        for subdirname in dirnames:
            print "FOUND DIRECTORY: ", os.path.join(dirname, subdirname)
        for filename in filenames:
            print "FOUND FILE: ", os.path.join(dirname, filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM