在嵌套文件夹中查找文件,并在 python 中将文件动态导入为模块

Find file in nested folder and dynamically import the file as a module in python

提问人:John Doe 提问时间:8/15/2023 最后编辑:John Doe 更新时间:8/15/2023 访问量:61

问:

假设我有一个文件结构,如下所示:

folder1
  --file1.py

  folderStart
    --start.py

  folder2
    --file2.py

  folderX
    --fileX.py
  ...

在 start.py 中,我动态获取文件的名称,例如:file_name = "file3"

我不知道“file3”在哪里,因为我没有得到它的文件路径。它可以是 folder1 中的任何位置或子文件夹:folder2、folderX 等。 然后,我需要动态导入“file3”,为此我需要知道它 start.py 的相对路径。

import_module(f"{file_path}")

如何找到“file3”及其路径,以便调用导入?

感谢您的任何回复,我是初学者,如果不清楚,很抱歉。尝试获取相对路径失败

**编辑:所有文件和文件夹都有随机名称,未排序 此外,folder1 上方有一个文件结构,我只需要查看 folder1 内部。

python-3.x 相对路径 导入模块

评论

0赞 JRiggles 8/15/2023
到目前为止,您尝试过什么?
0赞 lotus 8/15/2023
尝试 glob.glob(“**/**file3.py”, recursive=True)
0赞 rkochar 8/15/2023
如果你的文件是排序的(它们看起来是有排序的),你可以结合os package进行二进制搜索。这比 @lotus 之前的答案要好,因为它不会暴力搜索。
0赞 lotus 8/15/2023
@rkochar我认为这不是一个好主意,因为文件的顺序取决于操作系统,如果您事先进行排序,时间复杂度会更高
0赞 John Doe 8/15/2023
@rkochar 不幸的是,它们没有分类

答:

0赞 Unnikrishnan Namboothiri 8/15/2023 #1

这应该对你有所帮助

import os
def find_file(root_folder, target_file):
    for root, dirs, files in os.walk(root_folder):
        if target_file in files:
            return os.path.join(root, target_file)
    return None

root_folder = '/path/to/unknown/root/folder'
target_file = 'file_name.txt'

file_path = find_file(root_folder, target_file)

if file_path:
    print(f"File '{target_file}' found at: {file_path}")
else:
    print(f"File '{target_file}' not found in the specified folder.")```

评论

0赞 John Doe 8/15/2023
谢谢,这比上面建议的 glob 好吗?
0赞 Community 8/16/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。