Reputation: 321
I have a script.py located in a folder called subfolder1. This folder is inside a folder called mainfolder. There is another folder inside mainfolder called subfolder2. I would like for script.py to open an image inside subfolder2 and do some cropping etc, but I don't know how to get the directory right. I have tried:
import os
rel = "../subfolder2/1.bmp"
impath = os.path.abspath(rel)
im = Image.open(impath)
But the error message appears:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\****\\Desktop\\mainfolder\\subfolder2\\1.bmp'
By the way, I am using Windows.
Upvotes: 0
Views: 7439
Reputation: 92569
If your directory structure looks like this:
mainfolder/
subfolder1/
script.py
subfolder2/
1.bmp
... Then you can construct a path relative to the script.py
. Right now you are only working with a path relative to the current working directly where you have launched your shell command.
You can do something like this:
import os
scriptDir = os.path.dirname(__file__)
impath = os.path.join(scriptDir, '../subfolder2/1.bmp')
__file__
is a builtin attribute in the module, that tells you the filesystem path of that module.
Upvotes: 2