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.
process_image()
function is going to have to assume something — what should that be or what assumption should be made?