简体   繁体   中英

Python3 listing all files/directories on same level as certain folder name

I have a path like this:

/my/path/to/important_folder

on the same level, I have other files and folders that I want to list when I reach the same level as important_folder .

My folder could be deeper, so I need to traverse through the folders until I reach important_folder keep searching. Once found, list all files/folders in that same level.

How can I achieve this?

With os.walk , you can do this:

import os
for path, dirs, files in os.walk('/my/path'):
    if path == 'important_folder':
        for name in dirs + files:
            print(os.path.join(path, name))

Or you can use glob.iglob with recursive=True :

import glob
for name in glob.iglob('/my/path/**/important_folder/*', recursive=True):
    print(name)

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