简体   繁体   中英

How can I print folder/sub-folders and import files from them?

How can I print folder/sub-folder names and import files from each folder?

1.folder 1.1. folder 1.1.1.folder 1.1.1.1.folder 1.1.1.2.folder 1.1.2.folder 1.1.3.folder 1.2.folder 1.2.1.folder 1.2.2.folder

You can use os.listdir() to get all files/folders in a directory and then loop over each and do the same recursively. Something like:

import os
from queue import Queue

files = []

q = Queue()
q.put(PATH)

while not q.empty():
    path = q.get()
    
    for file in os.listdir(path):
        if os.path.isdir(file):
            print(file)
            q.put(file)
        else:
            files.append(file)

This would extract all files in each subdirectory to the files array and in the loop print each searched directory. Make sure to change PATH to your starting directory for the search.

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