使用相对路径导入Python脚本

使用相对路径导入Python脚本,python,path,Python,Path,我有一个从其目录加载图像的脚本,我希望能够从任何文件导入该脚本,该脚本仍然能够找到其图像。这样可能更清楚: A/ file1.py images/img.png B/ file2.py 在file1.py中: image = load_img("images/img.png") import file1 # here, I expect to be able to use file1.image 在file2.py中: image = load_img("images/img.p

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

  • A/

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

    • file2.py
file1.py中

image = load_img("images/img.png")
import file1
# here, I expect to be able to use file1.image
file2.py中

image = load_img("images/img.png")
import file1
# here, I expect to be able to use file1.image
但是在文件2中,相对路径是相对于
B/
目录的,因此找不到
images/img.png

无论从何处导入
file1.py
而不在此处写入绝对路径,如何使我的
image
变量可用?这样做的最佳实践是什么

提前感谢您的帮助或建议。

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

# Inside file1.py
import os

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

默认情况下,您不能这样做。 您需要使用sys.path.insert选项转到该文件夹,然后导入所需文件

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

print file1.image

在路径中使用“.”怎么样?我说“无论从哪里导入
file1
”。我以2个目录为例,但实际情况更为复杂(比如可以从任何项目导入的库)。这就是我所寻找的。谢谢