Answer the question
In order to leave comments, you need to log in
How to specify a relative path to a file through an external folder?
Hello. In a regular python script, I can specify the path to a file, which can be in any folder located in the same directory as the script itself. But how do I specify the path to the file if it is located in a folder that is one level higher than the one where the script is, without using the full absolute path?
Answer the question
In order to leave comments, you need to log in
>>> import os
>>> c = os.getcwd()
>>> c
'C:\\Users\\ashab'
>>> d = os.path.split(c)
>>> d
('C:\\Users', 'ashab')
>>> test_folder = r'C:\Program Files\Common Files\Adobe'
>>> d_test_folder = os.path.split(test_folder)
>>> d_test_folder
('C:\\Program Files\\Common Files', 'Adobe')
>>> d_test_folder[0]
'C:\\Program Files\\Common Files'
>>>
from pathlib import Path
print(Path.home())
print(Path.home().parent)
Try putting two dots in front of the file name:
test.txt -> ../test.txt
this will mean that your file is one level higher than your script
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question