使用相对路径导入Python脚本

2024-04-24 11:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从其目录加载图像的脚本,我希望能够从任何文件导入该脚本,并且该脚本仍然能够找到其图像。这样可能更清楚:

  • A/

    • file1.py
    • images/img.png
  • B/

    • file2.py

file1.py中:

image = load_img("images/img.png")

file2.py中:

import file1
# here, I expect to be able to use file1.image

但是在file2中,相对路径是相对于B/目录的,因此找不到images/img.png。你知道吗

我怎么能有我的image变量可用,不管我从哪里导入file1.py,而不在这里写一个绝对路径?这样做的最佳做法是什么?你知道吗

提前感谢您的帮助或建议。你知道吗


Tags: 文件topy图像imageimport目录脚本
2条回答

默认情况下不能这样做。 你需要使用系统路径插入选项转到该文件夹,然后导入所需文件

import sys
sys.path.insert(0, '../A/')
import file1

print file1.image

获取“file1.py”目录并构造路径:

# Inside file1.py
import os

filename = os.path.join(os.path.dirname(__file__), "images/img.png")
image = load_img(filename)

相关问题 更多 >