正在进行循环 - Python

时间:2017-07-05 07:02:35

标签: python dictionary

我有dictionary,其中包含文件/目录路径。在for循环中,我会检查路径是否链接到文件或目录。如果它是一个目录,我必须再次循环,但更深一层。

我必须这样做,直到我在dict中不再有任何dir路径。 我不知道dir有多少级别,我不想在其中创建冗余代码。

有人能帮助我吗?

示例:

# here i do have the top level for loop
for each_path in file_or_dir_paths.keys():
    # then i check if the path links to a dir
    # in dictionary[each_path] the date of the file/dir is stored
    # but this isnt important yet
    status = is_it_dir(each_path, dictionary[each_path])
    # status 0 means an empty dir
    if status == 0:
        del dictionary[each_path]
    # status 1 means a dir with files in it
    if status == 1:
        # and here i do have to do the loop again
        # which is redundant and will get deeper with every loop iteration
        dictionary[each_path] = for_loop_again
    # status 10 means path is a file
    if status == 10:
        # this section is not important right now
        dictionary[each_path] = True

1 个答案:

答案 0 :(得分:1)

最好使用Python的buildin函数walk()来遍历目录结构。 walk()将访问任何深度的所有子目录。这是你如何使用它。

from os import walk

# assume variable root contain your root path

for path, dirs, files in walk(root):
   # do what you need to do with the files and dirs

如果你想出于某种原因编写自己的遍历代码,那么你需要使用递归,你不能拥有固定数量的嵌套循环(正如你似乎所建议的那样)