Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access file in parent directory using python?

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?

like image 591
Edmund Carvalho Avatar asked Nov 15 '17 06:11

Edmund Carvalho


Video Answer


1 Answers

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.

like image 151
mikuszefski Avatar answered Sep 16 '22 13:09

mikuszefski