2

I want to get the parent directory of a file. This code doesn't work:

projectRoot = os.path.dirname(os.pardir(os.path.abspath(__file__)))

What's wrong?

(I am developing a django application, and use this variable in the settings file of my application)

Thanks.

Romain

rom
  • 3,592
  • 7
  • 41
  • 71

3 Answers3

5

You can access the parent directory by using ..

import os
os.path.join(os.path.dirname(__file__), os.pardir)

OR:

import os
split_limit = 1 if os.path.isdir(__file__) else 0
parent_dir = os.path.abspath(__file__).rsplit(os.path.sep, split_limit)[0]
karthikr
  • 97,368
  • 26
  • 197
  • 188
1

As simple as this:

import os
def get_parent_dir(file_path):
    return os.path.dirname(file_path)

To get the file_path of the script being run, you could do this:

import sys
file_path = sys.argv[0]
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • `os.path.dirname` appears to return the absolute *path* to the file, not the *name* of the file's immediate parent directory – 8bitjunkie Aug 29 '15 at 09:58
0

in our django project we use next structure: we have prodaction_settings.py where placed settings for prodaction server and all variables. on local machine in file settings.py

from os.path import dirname, abspath, join
TEST_DIR = dirname(abspath(__file__))
from production_settings import *

to add your local folder with templates:

TEMPLATE_DIRS = (
    join(TEST_DIR, 'tmpl'), 
)
Andy Dreamer
  • 51
  • 1
  • 3