How to access file in parent directory using python?

Viewed 13494

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?

4 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.

To get a path to a file in the parent directory of the current script you can do:

import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')

You can try this

import environ
environ.Path() - 1 + 'foo.txt'

to get the parent dir the below code will help you:

import os
os.path.abspath(os.path.join('..', os.getcwd()))
Related