Python模块运行时导入与文件路径不以运行脚本为相对基准问题
问题原因
导入异常原因
Python 搜索导入模块时依赖 sys.path 列表中的路径,从 root_dir 目录执行 main.py 时,Python 会自动将*进程启动时的工作目录(即 root_dir)*加入 sys.path,不会自动加入 sub_dir 的路径。因此在 module.py 中直接搜索 utils 模块时,只会在 sys.path 包含的路径下查找,找不到 root_dir/utils.py 就会报错,必须携带 sub_dir 前缀才能以 root_dir 为基准定位到正确的模块。
文件读取异常原因
open() 函数使用相对路径时,路径基准是进程的当前工作目录,不是当前执行的 .py 文件本身所在的目录。你在 root_dir 下启动 main.py 时,进程工作目录默认为 root_dir,直接写 open('file.txt','r') 会尝试读取 root_dir/file.txt,自然找不到对应文件,必须补全 sub_dir 前缀才能定位到正确文件。
解决方案
导入问题解决方案
- 方案1:使用包内相对导入
在sub_dir目录下新增一个空的__init__.py文件,将sub_dir标识为 Python 包,之后在module.py中直接写from .utils import function即可正常导入。 - 方案2:手动将
sub_dir加入搜索路径
在入口文件main.py的开头添加以下代码,把sub_dir路径临时加入sys.path:
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), 'sub_dir'))
之后 module.py 中就可以直接用 from utils import function 导入。
文件读取问题解决方案
不要使用硬编码的相对路径,基于当前 .py 文件的内置变量 __file__ 动态拼接绝对路径,该变量存储了当前 .py 文件的绝对路径,不受进程启动位置影响:
- 兼容所有Python3版本的写法:
import os # 获取当前utils.py所在的目录路径 current_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(current_dir, 'file.txt') with open(file_path, 'r') as f: # 读取逻辑
- Python 3.4及以上版本更简洁的pathlib写法:
from pathlib import Path current_dir = Path(__file__).absolute().parent file_path = current_dir / 'file.txt' with open(file_path, 'r') as f: # 读取逻辑
内容的提问来源于stack exchange,提问作者An Ignorant Wanderer
相关产品推荐
相关产品推荐

