I am trying to know more about how paths work in python and I encountered the next problem.
When I try to call the full path I use the following -> "./Folder/archive2", and this works perfectly well when my .py file is in the same directory as the folder containing this 'archive2', but lets say the following:
- Archive1 is in Folder1 (both archives are .py files)
- Archive2 is in Folder2
- Folder1 and Folder2 are in "RandomDirectory"
How can I get the path of Archive2 in Archive1 if they are in the same RandomDirectory but in different folders. Of course, copying the path is not an option because I want it to work on any computer so something like "./Folder/archive" would be great, so if I run the .py in other computer it would work as normal.
Thanks for reading.
CodePudding user response:
Use ..
to refer to the parent of the current directory.
If your working directory is Archive1
, then:
..
refers toFolder1
../..
refers toRandomDirectory
../../Folder2
refers toRandomDirectory/Folder2
- and
../../Folder2/Archive2
refers toRandomDirectory/Folder2/Archive2
.
CodePudding user response:
if you have a structure like this:
Randomdirectory
├── Folder1
│ └── Archive1.py
└── Folder2
└── Archive2.py
you can access Archive2.py
from Archive1.py
like this:
# code in Archive1.py
from pathlib import Path
print(Path('../Folder2/Archive2.py').exists())
CodePudding user response:
In general you can use os
library like this:
import os.path as pt
archive2_path = pt.join(pt.split(pt.dirname(pt.abspath(__file__)))[0], 'Folder2/Archive2.py')
In this case archive2_path
is absolute path of Archive2.