Python中如何从内容根目录获取文件路径?场景化路径查找咨询
如何在app.py中查找指定文件名的路径
当然可以,你可以借助Python的标准库在app.py中实现这个需求,以下是两种实用方法:
使用
os.walk遍历目录树os.walk会递归遍历当前工作目录下的所有子目录,你可以逐一检查文件名是否匹配目标,找到后返回完整路径。示例代码:import os def get_file_path(target_filename): # 获取app.py所在的工作目录(directory 1) root_directory = os.getcwd() for dir_path, _, file_names in os.walk(root_directory): if target_filename in file_names: return os.path.join(dir_path, target_filename) return None # 未找到文件时返回None # 查找example.txt的路径 target_path = get_file_path("example.txt") if target_path: print(f"找到文件:{target_path}") else: print("未找到目标文件")使用
pathlib模块(Python 3.4+)pathlib提供了更简洁的面向对象式文件操作,通过递归匹配可以快速定位目标文件:from pathlib import Path def get_file_path(target_filename): root_directory = Path.cwd() # 递归遍历所有文件,匹配目标文件名 for file_path in root_directory.rglob("*"): if file_path.is_file() and file_path.name == target_filename: return str(file_path) return None target_path = get_file_path("example.txt") if target_path: print(f"找到文件:{target_path}") else: print("未找到目标文件")
注意:如果工作目录下存在多个同名的example.txt,上述代码只会返回第一个匹配的文件路径。若需要收集所有匹配文件,可以将返回值改为列表,把所有符合条件的路径存入其中。
内容的提问来源于stack exchange,提问作者CoolMathematician
相关产品推荐
相关产品推荐

