提问人:John Doe 提问时间:8/15/2023 最后编辑:John Doe 更新时间:8/15/2023 访问量:61
在嵌套文件夹中查找文件,并在 python 中将文件动态导入为模块
Find file in nested folder and dynamically import the file as a module in python
问:
假设我有一个文件结构,如下所示:
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 内部。
答:
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.")```
评论