Get parent of current directory from Python script
I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts
the desire path in this case is /home/kristina/desire-directory
I know sys.path[0]
from sys
. But I don't want to parse sys.path[0]
resulting string. Is there any another way to get parent of current directory in Python?
python sys sys.path
add a comment |
I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts
the desire path in this case is /home/kristina/desire-directory
I know sys.path[0]
from sys
. But I don't want to parse sys.path[0]
resulting string. Is there any another way to get parent of current directory in Python?
python sys sys.path
add a comment |
I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts
the desire path in this case is /home/kristina/desire-directory
I know sys.path[0]
from sys
. But I don't want to parse sys.path[0]
resulting string. Is there any another way to get parent of current directory in Python?
python sys sys.path
I want to get the parent of current directory from Python script. For example I launch the script from /home/kristina/desire-directory/scripts
the desire path in this case is /home/kristina/desire-directory
I know sys.path[0]
from sys
. But I don't want to parse sys.path[0]
resulting string. Is there any another way to get parent of current directory in Python?
python sys sys.path
python sys sys.path
edited Jun 1 '16 at 15:53
vaultah
27.4k976104
27.4k976104
asked May 13 '15 at 15:07
Fedorenko KristinaFedorenko Kristina
1,15211116
1,15211116
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
Using os.path
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
You could also use the pathlib
module (available in Python 3.4 or newer).
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
->Path(".").resolve()
. This also works when there isn't a__file__
because you started in the interactive interpreter.
– Navith
May 13 '15 at 16:17
if script is in/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return/scripts
instead
– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all othersos.blabla
isn't work for me but this solution. Many many thanks!
– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
add a comment |
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
add a comment |
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
add a comment |
You can use Path.parent
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
add a comment |
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
add a comment |
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30218802%2fget-parent-of-current-directory-from-python-script%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Using os.path
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
You could also use the pathlib
module (available in Python 3.4 or newer).
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
->Path(".").resolve()
. This also works when there isn't a__file__
because you started in the interactive interpreter.
– Navith
May 13 '15 at 16:17
if script is in/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return/scripts
instead
– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all othersos.blabla
isn't work for me but this solution. Many many thanks!
– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
add a comment |
Using os.path
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
You could also use the pathlib
module (available in Python 3.4 or newer).
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
->Path(".").resolve()
. This also works when there isn't a__file__
because you started in the interactive interpreter.
– Navith
May 13 '15 at 16:17
if script is in/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return/scripts
instead
– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all othersos.blabla
isn't work for me but this solution. Many many thanks!
– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
add a comment |
Using os.path
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
You could also use the pathlib
module (available in Python 3.4 or newer).
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
Using os.path
To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__
.
Inside the script use os.path.abspath(__file__)
to obtain the absolute path of the script, and call os.path.dirname
twice:
from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory
Basically, you can walk up the directory tree by calling os.path.dirname
as many times as needed. Example:
In [4]: from os.path import dirname
In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'
In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'
If you want to get the parent directory of the current working directory, use os.getcwd
:
import os
d = os.path.dirname(os.getcwd())
Using pathlib
You could also use the pathlib
module (available in Python 3.4 or newer).
Each pathlib.Path
instance have the parent
attribute referring to the parent directory, as well as the parents
attribute, which is a list of ancestors of the path. Path.resolve
may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute
instead if that isn't a desired behaviour.
Path(__file__)
and Path()
represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')
and to get the parent directory of the current working directory
from pathlib import Path
d = Path().resolve().parent
Note that d
is a Path
instance, which isn't always handy. You can convert it to str
easily when you need it:
In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'
edited Sep 30 '16 at 21:32
answered May 13 '15 at 15:08
vaultahvaultah
27.4k976104
27.4k976104
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
->Path(".").resolve()
. This also works when there isn't a__file__
because you started in the interactive interpreter.
– Navith
May 13 '15 at 16:17
if script is in/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return/scripts
instead
– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all othersos.blabla
isn't work for me but this solution. Many many thanks!
– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
add a comment |
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
->Path(".").resolve()
. This also works when there isn't a__file__
because you started in the interactive interpreter.
– Navith
May 13 '15 at 16:17
if script is in/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return/scripts
instead
– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all othersos.blabla
isn't work for me but this solution. Many many thanks!
– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Thanks! It works!
– Fedorenko Kristina
May 13 '15 at 15:10
Path(__file__).resolve().parent
-> Path(".").resolve()
. This also works when there isn't a __file__
because you started in the interactive interpreter.– Navith
May 13 '15 at 16:17
Path(__file__).resolve().parent
-> Path(".").resolve()
. This also works when there isn't a __file__
because you started in the interactive interpreter.– Navith
May 13 '15 at 16:17
if script is in
/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return /scripts
instead– LetsPlayYahtzee
Jun 1 '16 at 14:12
if script is in
/scripts
folder, like` /home/kristina/desire-directory/scripts/myScript.py` the first solution will not return the desired directory, it will return /scripts
instead– LetsPlayYahtzee
Jun 1 '16 at 14:12
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
@LetsPlayYahtzee: thanks, I revised my answer
– vaultah
Jun 1 '16 at 16:00
all others
os.blabla
isn't work for me but this solution. Many many thanks!– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
all others
os.blabla
isn't work for me but this solution. Many many thanks!– Tiến Nguyễn Hoàng
Jul 5 '18 at 2:10
add a comment |
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
add a comment |
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
add a comment |
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
answered Apr 29 '16 at 13:10
akashbwakashbw
700710
700710
add a comment |
add a comment |
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
add a comment |
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
add a comment |
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')
answered May 13 '15 at 15:51
corvidcorvid
5,14463678
5,14463678
add a comment |
add a comment |
You can use Path.parent
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
add a comment |
You can use Path.parent
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
add a comment |
You can use Path.parent
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
You can use Path.parent
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
edited Sep 21 '16 at 14:41
wasthishelpful
10.9k93047
10.9k93047
answered Sep 21 '16 at 13:33
Gavriel CohenGavriel Cohen
1,1181317
1,1181317
add a comment |
add a comment |
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
add a comment |
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
add a comment |
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
from os.path import dirname
from os.path import abspath
def get_file_parent_dir_path():
"""return the path of the parent directory of current file's directory """
current_dir_path = dirname(abspath(__file__))
path_sep = os.path.sep
components = current_dir_path.split(path_sep)
return path_sep.join(components[:-1])
answered Mar 10 '16 at 16:54
beingzybeingzy
4113
4113
add a comment |
add a comment |
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
add a comment |
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
add a comment |
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
'..'
returns parent of current directory.
import os
os.chdir('..')
Now your current directory will be /home/kristina/desire-directory
.
answered Nov 14 '18 at 11:08
MarcinMarcin
12
12
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30218802%2fget-parent-of-current-directory-from-python-script%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown