0

So, I have a following file structure:

main.py
├── net
    └── src
        ├── file.py
        └── dataset
            └── image.jpg 

I use import net.src.file to import file.py into main.py, that part works. A function in file.py needs the image.jpg. However, for some reason, it can't utilize relative path, i. e. open("dataset/img.jpg"), it needs the full path, as if we were going from main.py - open("net/src/dataset/image.jpg").

Can I import a file and use its functions and force those functions to get a path from their respective directory? (Not root but src)

I don't want to just give it the path from main.py, because I would have to redo a lot of functions, the code is basically a combination of two codebases (It tries to use file.py as a library). Functions work fine when executing file.py standalone, but when imported from main.py it gives the error - FileNotFoundError: [Errno 2] No such file or directory: open("dataset/img.jpg").

Laura
  • 1
  • Welcome to Stack Overflow. "However, for some reason, it can't utilize relative path" It *is* using a relative path. A path that *isn't* relative - i.e., that is *absolute* - would start with a `/` (or a drive letter, depending on the operating system). However, when you use a relative path to open a file, it is only ever relative to the *current working directory* of the *process* that is running - not any particular source code file. Also, *none of this has anything to do with* "importing", or the `import` keyword in Python. – Karl Knechtel Jan 25 '22 at 22:45
  • However, all is not lost. Please see the linked duplicate. Python can tell you a relative path from the current working directory *to* the source code file, and you can use this to locate the resource file. – Karl Knechtel Jan 25 '22 at 22:48
  • Thank you very much, it seems the linked duplicate has what I need! – Laura Jan 25 '22 at 23:35

0 Answers0