I am trying to access a text file in the parent directory,
Eg : python script is in codeSrc & the text file is in mainFolder.
G:\mainFolder\codeSrc\fun.py
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With