How to access file in parent directory using python?

Edmund Carvalho picture Edmund Carvalho · Nov 15, 2017 · Viewed 10k times · Source

I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

G:\mainFolder\codeSrc\fun.py

desired file path:

G:\mainFolder\foo.txt

I am currently using this syntax with python 2.7x,

import os 
filename = os.path.dirname(os.getcwd())+"\\foo.txt"

Although this works fine, is there a better (prettier :P) way to do this?

Answer

mikuszefski picture mikuszefski · Nov 15, 2017

While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write

os.path.join( os.getcwd(), '..', 'foo.txt' )

...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.