Nikko
Nikko

Reputation: 1572

Read from different directory with respect to home directory

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

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

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

Blue Alder
Blue Alder

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

Related Questions