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
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, '..', '..'))
>>> 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
.
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