Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent directory of a specific file

Tags:

python

There is a file a.py.

The location is /home/user/projects/project1/xxx/a.py.

If I call os.getcwd(), it gives me /home/user/projects/project1/xxx/. But I want to reach /home/user/projects/project1. How can i do this in Python?

Edit : I think i must be more clear. i want this for my Django project.

i use these codes in my settings.py:

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

then i use fallowing code to specify where my static file folder is. :

os.path.join(PROJECT_PATH,'statics'),

my settings.py file is under: /home/user/projects/project1/xxx/settings.py

my static file folder is under same dir as settings.py.

now i want to move this folder to /home/user/projects/project1

what should i do with code that in settings.py

thank you

like image 569
alioguzhan Avatar asked Oct 15 '12 11:10

alioguzhan


2 Answers

from os.path import dirname

print(dirname(dirname(__file__)))

Each time you call dirname it gives you parent directory. Call as many times as necessary.

Alternatively you can do following:

normpath(join(path1, '..', '..'))
like image 75
Kugel Avatar answered Oct 11 '22 05:10

Kugel


>>> import os
>>> os.getcwd()
'/tmp/test'
>>> os.chdir('..')
>>> os.getcwd()
'/tmp'
>>> 

The dot dot (..) represents the parent directory. Because relative path names specify a path starting in the current directory.

See the documentation of os.chdir.

like image 31
avasal Avatar answered Oct 11 '22 04:10

avasal