D
D
Danil Samodurov2021-11-16 21:39:56
Python
Danil Samodurov, 2021-11-16 21:39:56

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

3 answer(s)
A
Alexander, 2021-11-16
@samodurOFF

>>> 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'
>>>

A
Alan Gibizov, 2021-11-16
@phaggi

from pathlib import Path
print(Path.home())
print(Path.home().parent)

I highly recommend learning.
It's especially cool to do Path / Path / Path. Just in line.

Y
YariKartoshe4ka, 2021-11-16
@YariKartoshe4ka

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 question

Ask a Question

731 491 924 answers to any question