Using os.walk in order to recurse into folders in Python

谁都会走 提交于 2020-02-15 20:20:26

问题


I have the following code as part of a Python file, and it traverses .py files in the folder called controllers, and preforms some operations with them.

This is my prototype, but now I want to use os.walk to recurse into the folders.

controller_folder_path = "applications/%s/controllers/*.py" % application_name
for module_path in glob.glob(controller_folder_path):
    print module_path

Any help?


回答1:


import os

controller_folder_path = "applications/%s/controllers" % application_name
for root, dirs, files in os.walk(controller_folder_path):
    for module_path in files:
        module_path = os.path.join(root, module_path)
        if module_path.endswith('.py'):
            print module_path



回答2:


os.walk will return an iterable of 3-tuples for every directory and subdirectory in the specified top directory.

from os import walk

dirs = walk('/top/directory/here')
for path_from_top, subdirs, files in dirs:
    for f in files:
        if f.endswith('py'):
            print str(path_from_top) + '/' + str(f)


来源:https://stackoverflow.com/questions/27495612/using-os-walk-in-order-to-recurse-into-folders-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!