Python:在当前目录及其所有父目录中搜索文件

新手上路,请多包涵

是否有一个内置模块可以在当前目录以及所有超级目录中搜索文件?

如果没有该模块,我将不得不列出当前目录中的所有文件,搜索有问题的文件,如果文件不存在则递归向上移动。有没有更简单的方法来做到这一点?

原文由 gaganso 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 735
2 个回答

好吧,这不是很好实施,但会起作用

使用 listdir 获取当前目录中的文件/文件夹列表,然后在列表中搜索您的文件。

如果存在循环中断,但如果不存在,则使用 os.path.dirnamelistdir 进入父目录。

如果 cur_dir == '/' 父母dir for "/" 返回 "/" cur_dir == parent_dir

 import os
import os.path

file_name = "test.txt" #file to be searched
cur_dir = os.getcwd() # Dir from where search starts can be replaced with any path

while True:
    file_list = os.listdir(cur_dir)
    parent_dir = os.path.dirname(cur_dir)
    if file_name in file_list:
        print "File Exists in: ", cur_dir
        break
    else:
        if cur_dir == parent_dir: #if dir is root dir
            print "File not found"
            break
        else:
            cur_dir = parent_dir

原文由 Harwee 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是另一个,使用 pathlib:

 from pathlib import Path

def find_upwards(cwd: Path, filename: str) -> Path | None:
    if cwd == Path(cwd.root) or cwd == cwd.parent:
        return None

    fullpath = cwd / filename

    return fullpath if fullpath.exists() else find_upwards(cwd.parent, filename)

# usage example:
find_upwards(Path.cwd(), "helloworld.txt")

(这里使用一些 Python 3.10 类型语法,如果你使用的是早期版本,你可以安全地跳过它)

原文由 David Vujic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题