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

后端 未结 2 475
情歌与酒
情歌与酒 2021-01-23 09:06

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 prot

相关标签:
2条回答
  • 2021-01-23 09:37
    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
    
    0 讨论(0)
  • 2021-01-23 09:46

    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)
    
    0 讨论(0)
提交回复
热议问题