【问题标题】:Doesn't append to the list不附加到列表
【发布时间】:2021-11-29 19:07:18
【问题描述】:

我写了一个简单的搜索功能。还创建了一个空列表以获得结果。

def simple_search(path,filename) :
    found_files = []
    try:
        folders = next(os.walk(path))[1]
        for i in next(os.walk(path))[2]:
            if filename in i:
                print(path+i)
                found_files.append(path+i)
        for folder in folders:
                folder_path = path + '\\' + folder
                simple_search(folder_path, filename)     
    except StopIteration:
        pass
    return found_files

代码不会将任何内容附加到列表中,并且函数会返回一个空列表。 打印语句 (print(path+i)) 有效,因此 if 条件似乎没有任何问题。 提前致谢。

【问题讨论】:

  • 你干嘛next(os.walk(path))
  • 你为什么要手动尝试使用递归来遍历目录? os.walk已经这样做了。你能用你自己的话解释一下你要做什么吗?
  • 除了上面列出的错误之外,我还能够将一个文件附加到在我的机器上运行它的列表中。

标签: python list return append


【解决方案1】:

您的问题是您在simple_search 内递归调用simple_search(folder_path, filename) 时忽略了返回值。您可以将行更改为:

findings = simple_search(folder_path, filename)
found_files.extend(findings)  # adds the values of the iterable (list in this case)

但是,正如 juanpa.arrivillaga 在他的评论中已经指出的那样,os.walk 确实已经遍历了子目录。

通过自上而下或自下而上遍历目录树来生成目录树中的文件名。 (https://docs.python.org/3/library/os.html#os.walk)

import os

def simple_search(path, filename) :
    
    found_files = []

    for root, _, files in os.walk(path):

        for file in files:
            if filename in file:
                full_path = os.path.join(root, file)
                # print(full_path)
                found_files.append(full_path)

    return found_files

found_files = simple_search(r"D:\projects\test\data", "test.csv")
print(found_files)

您也可以只使用Path.glob,而不是使用os.walk。这使您的代码更简洁,更易于维护:

from pathlib import Path

def simple_search(path, filename):  # theoretically, you don't even need a function
    return [str(p) for p in Path(path).glob(f"**/*{filename}*")]

found_files = simple_search(r"D:\projects\test\data", "test.csv")
print(found_files)

建议:请尽量避免不必要的递归。递归总是增加代码的复杂性,难以维护和调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多