I have a Python file in another location that requires an image file path. Here is the file structure:
Main_Dir
- main.py
- test.jpg
- Second_Dir
- other.py
My main.py
is calling a function in other.py
and passing "test.jpg"
as an argument. Obviously, other.py
cannot see this image as it isn't in its directory. Is there a way to do this so that other.py
uses the test.jpg
without having to pass the absolute path?
main.py
process_image("test.jpg")
other.py
def process_image(image_path):
rotate(image)
a*b = c
....
Error:
No such file or directory: 'test.jpg'
CodePudding user response:
You probably want to use the 'absolute path' of the file, which is the full path which will work from any location on the same computer:
from pathlib import Path
process_image(Path("test.jpg").absolute())
Even better might be .resolve()
, which will also resolve any symbolic links, and just give you the 'real' path of the object being passed.
process_image(Path("test.jpg").resolve())
However, a simple import won't change the working directory of your script - the script wouldn't simply use its own location as a reference. So, you may still have problems, if you don't start main.py
in the folder it is actually in.
To solve that, get the location of the main.py
script when you first start the program:
location = Path(__file__).parent()
my_file = (location / 'test.jpg').resolve()
process_image(my_file)
This works because __file__
will contain the filename of the script it is called from, .parent()
gets the parent folder (i.e. the folder the script is in) and the rest is the same as before. Just note that Path('dir') / 'name.ext'
is just a nice way of constructing a path - Python allows 'dividing' a Path
by a string to extend the path.
Note: don't worry about forward slashes you may see in a resolved path. Although Windows doesn't always support the use of forward slashes, Python functions do (unless you use a Python function to directly execute some Windows command). Forward slashes are the standard on every OS except Windows, which is why Python defaults to it - it's not a bad idea to use them for several reasons.