Reputation: 1572
I want to read a file in a directory outside of a key environment directory. Suppose I have two directories
- folder1
- text1.txt
- folder2
- text2.txt
and I have set:
$ export HOME = ".../folder1/"
In Python:
import os
home = os.getenv("HOME")
How will I access folder2
with respect to home
directory, like reading text2.txt
?
Upvotes: 0
Views: 45
Reputation: 20490
You can use os.path.join to navigate to the file
path = os.path.join(home, '..', 'folder2', 'text2.txt')
print(path)
The output will be
../folder1/../folder2/text2.txt
That's because we need to go one level back by ..
to come out of folder1
, and then go into folder2/text2.txt
Upvotes: 2
Reputation: 101
Could you not reference it through a relative path and concatenation?
ie
import os
home = os.getenv("HOME")
folder2 = home + '/../folder2/'
Upvotes: 2