0

I have a script that loads an image from its directory, and I want to be able to import that script from any file, with this script still being able to find its image. Probably clearer that way:

  • A/

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

    • file2.py

In file1.py:

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

In file2.py:

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

But in file2, the relative path is relative to B/ directory, and images/img.png is therefore not found.

How can I have my image variable available, no matter from where I import file1.py without writing an absolute path here ? What's the best practice to do so ?

Thanks in advance for any help or advice.

2
  • how about you just use ".." in your path? Commented Jan 7, 2019 at 10:20
  • I said "no matter from where I import file1". I made 2 directories as an example, but real case is more complex (like a library that could be imported from any project). Commented Jan 7, 2019 at 10:52

2 Answers 2

1

Get the directory of "file1.py" and construct the path:

# Inside file1.py
import os

filename = os.path.join(os.path.dirname(__file__), "images/img.png")
image = load_img(filename)
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was looking for. Thanks
0

You can not do it by default. u need to use sys.path.insert option to go to that folder then import required file

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

print file1.image

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.