Reputation: 879
Say I am running a Python script in C:\temp\templates\graphics
. I can get the current directory using currDir = os.getcwd()
, but how can I use relative path to move up in directories and execute something in C:\temp\config
(note: this folder will not always be in C:\
)?
Upvotes: 1
Views: 1559
Reputation: 465
>>> os.getcwd()
'/Users/user/code'
>>> os.chdir('..')
>>> os.getcwd()
'/Users/user'
Upvotes: 1
Reputation: 5362
Try this one:
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "config")
Upvotes: 0
Reputation: 168866
It isn't exactly clear what you are trying to do, here are two alternatives:
To change your process's current working directory "up" the path:
os.chdir('../../config')
Or, to open a file using a relative pathname:
with open('../../config/my_config.ini') as cfg_file:
pass
Of course, if you do change your current working directory, then your open()
argument should change, also:
os.chdir('../../config')
with open('my_config.ini') as cfg_file:
pass
Upvotes: 0