如何在被导入的sender.py中相对自身路径打开template.html?
如何在被导入的模块中相对于自身路径引用文件?
你的文件结构:
/email_sender/sender.py /email_sender/template.html main.py
当在main.py中导入sender.py时,直接用open('template.html')会基于当前工作目录(即main.py所在目录)查找文件,导致找不到目标文件。要相对于sender.py的位置引用template.html,可以用以下两种方法:
方法1:使用os.path模块(兼容所有Python版本)
在sender.py中写入以下代码:
import os # 获取sender.py所在的绝对目录 module_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接template.html的路径 template_path = os.path.join(module_dir, 'template.html') with open(template_path, 'r') as f: html = f.read()
方法2:使用pathlib模块(Python3.4+ 推荐)
pathlib提供了更直观的路径操作方式,代码更简洁:
from pathlib import Path # 获取sender.py所在的绝对目录 module_dir = Path(__file__).parent.resolve() # 拼接template.html的路径 template_path = module_dir / 'template.html' with open(template_path, 'r') as f: html = f.read()
原理说明
__file__是Python模块的内置变量,存储了当前模块(sender.py)的路径。- 通过
os.path.dirname()或Path(__file__).parent可以获取模块所在的目录,再拼接目标文件名,就能得到基于模块位置的绝对路径,不受运行脚本的工作目录影响。
内容的提问来源于stack exchange,提问作者LucasSeveryn
相关产品推荐
相关产品推荐

