Parent Directo Y

💣 👉🏻👉🏻👉🏻 ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻
Sign up or log in to view your list.
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.
If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.
Mridang Agarwalla
Mridang Agarwalla 38.1k●6767 gold badges●202202 silver badges●354354 bronze badges
where yourpath is the path you want the parent for.
kender
kender 80k●2424 gold badges●9999 silver badges●144144 bronze badges
Neuron
3,822●33 gold badges●2424 silver badges●4444 bronze badges
Your answer is correct but convoluted; os.path.dirname is the function for this, like a+=5-4 is more convoluted than a+=1. The question requested only the parent directory, not whether is exists or the true parent directory assuming symbolic links get in the way. – tzot May 24 '10 at 12:03
I tried to change the code snippet to os.pardir, but unfortunately Stack Overflow "Edits must be at least 6 non-space characters". It seems smart enough to detect whitespace padding; maybe the OP can correct this someday... – monsur Aug 9 '12 at 15:27
@tzot: unfortunately os.path.dirname gives different results depending on whether a trailing slash is included in the path. If you want reliable results you need to use the os.path.join method in answer above. – Artfunkel Jun 28 '13 at 10:32
@Artfunkel Thanks. Your comment should be appended in the answer for its completeness' sake. – tzot Jun 29 '13 at 8:18
Since this is apparently complicated enough to warrant a StackOverflow question, I feel that this should be added to the os.path library as a built-in function. – antred Mar 4 '16 at 12:44
Caveat: os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender's answer using os.path.join(yourpath, os.pardir).
Wai Yip Tung
Wai Yip Tung 16.3k●99 gold badges●4040 silver badges●4646 bronze badges
LarsH
25.9k●88 gold badges●7979 silver badges●138138 bronze badges
os.path.dirname(r'C:\Program Files') what? Python's just giving you the directory where the file 'Program Files' would be. What's more, it doesn't even have to exist, behold: os.path.dirname(r'c:\i\like\to\eat\pie') outputs 'c:\\i\\like\\to\\eat' – Nick T May 18 '10 at 19:28
The original poster does not state that the directory have to exist. There are a lot of pathname methods that does nothing but string manipulation. To verify if the pathname actually exist requires a disk access. Depends on the application this may or may not be desirable. – Wai Yip Tung May 18 '10 at 19:45
this solution is sensitive to trailing os.sep. Say os.sep=='/'. dirname(foo/bar) -> foo, but dirname(foo/bar/) -> foo/bar – marcin Sep 10 '12 at 13:28
That's by design. It comes down to the interpretation of a path with a trailing /. Do you consider "path1" equals to "path1/"? The library use the most general interpretation that they are distinct. In some context people may want to treat them as equivalent. In this case you can do a rstrip('/') first. Had the library pick the other interpretation you will lost fidelity. – Wai Yip Tung Sep 11 '12 at 16:57
@Ryan, I don't know about that. There is an entire RFC 1808 written to address the issue of relative path in URI and all the subtlety of the presence and absence of a trailing /. If you know of any documentation that says they should be treated equivalent in general please point it out. – Wai Yip Tung Jul 24 '14 at 15:12
You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)
Your Python version is less than 3.4.
You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.
If none of the above apply, use Pathlib.
If you don't know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I've highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.
Navigating inside a directory tree:
wp-overwatch.com
wp-overwatch.com 6,610●33 gold badges●3535 silver badges●4444 bronze badges
This is the only sane answer. If you're forced to use Python 2, just pip install pathlib2 and use the backport. – Navin Nov 2 '17 at 5:51
This solution is NOT sensitive to trailing os.sep! – Dylan F Jun 18 '18 at 15:08
You don't really have to "worry about existing code generating errors if it were to use a Pathlib object" because you can just wrap the pathlib object: path_as_string = str(Path()). – John Nov 22 '20 at 21:33
ivo
ivo 3,941●55 gold badges●3030 silver badges●4141 bronze badges
Kenly
16.6k●55 gold badges●3636 silver badges●5252 bronze badges
This only gets the parent of the CWD, not the parent of an arbitrary path as the OP asked. – Sergio Jun 4 '13 at 14:05
Add the double dots at the end of your URL and it will work E.g os.path.abspath(r'E:\O3M_Tests_Embedded\branches\sw_test_level_gp\test_scripts\..\..') Result: E:\\O3M_Tests_Embedded\\branches – Arindam Roychowdhury Dec 2 '15 at 11:31
where yourpath is the path you want the parent for.
But this solution is not perfect, since it will not handle the case where yourpath is an empty string, or a dot.
This other solution will handle more nicely this corner case:
Here the outputs for every case that can find (Input path is relative):
Input path is absolute (Linux path):
benjarobin
benjarobin 4,154●2424 silver badges●2121 bronze badges
Normalizing the path is always a good practice, especially when doing cross-platform work. – DevPlayer Jan 28 '16 at 13:50
This is the correct answer! It keeps relative paths relative. Thanks! – Maxim Oct 24 '17 at 19:06
@Maxim This solution was not perfect, I did improved it since the orginal solution does not handle one case – benjarobin Oct 27 '17 at 9:10
@benjarobin Yes, I hadn't thought of the corner case. Thanks. – Maxim Oct 27 '17 at 11:16
os.path.split(os.path.abspath(mydir))[0]
Dan Menes
Dan Menes 6,091●11 gold badge●3131 silver badges●3535 bronze badges
This won't work for paths which are to a directory, it'll just return the directory again. – Anthony Briggs Feb 20 '13 at 2:37
@AnthonyBriggs, I just tried this using Python 2.7.3 on Ubuntu 12.04 and it seems to work fine. os.path.split(os.path.abspath("this/is/a/dir/"))[0] returns '/home/daniel/this/is/a' as expected. I don't at the moment have a running Windows box to check there. On what setup have you observed the behavior that you report? – Dan Menes Feb 22 '13 at 0:59
You could do parentdir = os.path.split(os.path.apspath(dir[:-1]))[0]. This - I am certain - works because if there is a slash on the end, then it is removed; if there is no slash, this will still work (even if the last part of the path is only one char long) because of the preceding slash. This of course assumes that the path is proper and not say something like /a//b/c///d//// (in unix this is valid still), which in most cases they are (proper) especially when you do something like os.path.abspath or any other os.path function. – dylnmc Oct 4 '14 at 16:51
Also, to counteract a lot of slashes on the end, you could just write a small for loop that removes those. I'm sure there could even be a clever one-liner to do it, or maybe do that and os.path.split in one line. – dylnmc Oct 4 '14 at 16:57
@Den Menes I just saw you comment. It doesn't work if you have something like os.path.split("a/b//c/d///") and, for example, cd //////dev////// is equivalent to cd /dev/` or cd /dev; all of these are valid in linux. I just came up with this and it may be useful, though: os.path.split(path[:tuple(ind for ind, char in enumerate(path) if char != "/" and char != "\\")[-1]])[0]. (This essentially searches for the last non-slash, and gets the substring of the path up to that char.) I used path = "/a//b///c///d////" and then ran the aforementioned statement and got '/a//b///c'. – dylnmc Oct 4 '14 at 17:13
Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams 707k●136136 gold badges●12451245 silver badges●12901290 bronze badges
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
Grandpapa
Grandpapa 149●11 silver badge●55 bronze badges
Soumendra
Soumendra 1,185●22 gold badges●2323 silver badges●4141 bronze badges
If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:
os.path.split(os.path.dirname(currentDir))[1]
i.e. with a currentDir value of /home/user/path/to/myfile/file.ext
8bitjunkie
8bitjunkie 11.6k●99 gold badges●4949 silver badges●6868 bronze badges
os.path.basename(os.path.dirname(current_dir)) also works here. – DevPlayer Jan 28 '16 at 13:58
Suppose we have directory structure like
We want to access the path of "P" from the directory R then we can access using
We want to access the path of "Q" directory from the directory R then we can access using
Rakesh Chaudhari
Rakesh Chaudhari 2,508●11 gold badge●2121 silver badges●2323 bronze badges
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
Miguel Mota
Miguel Mota 18.2k●55 gold badges●3939 silver badges●5555 bronze badges
import os.path
os.path.abspath(os.pardir)
Washington Botelho
Washington Botelho 586●55 silver badges●99 bronze badges
This presumes you want the parent directory of "the current working directory" and not the parent directory any path in general. – DevPlayer Jan 28 '16 at 14:00
Just adding something to the Tung's answer (you need to use rstrip('/') to be more of the safer side if you're on a unix box).
But, if you don't use rstrip('/'), given your input is
which is probably not what you're looking at as you want both "../data/replies/" and "../data/replies" to behave the same way.
samsamara
samsamara 4,298●55 gold badges●3333 silver badges●5858 bronze badges
I would recommend to not use "input" as a variable/reference. It is a built-in function. – DevPlayer Jan 28 '16 at 14:01
You can use this to get the parent directory of the current location of your py file.
Eros Nikolli
Eros Nikolli 861●11 gold badge●66 silver badges●88 bronze badges
jofel
3,032●1414 silver badges●2727 bronze badges
That suggestion often leads to bugs. os.getcwd() is often NOT where "your py file" is. Think packages. If I "import some_package_with_subpackages" many modules will not be in that package's top-most directory. os.getcwd() returns where you execute top-most script. And that also presumes you are doing it from a command line. – DevPlayer Jan 28 '16 at 13:56
Like DevPlayer noted os.getcwd() is not necessarily the location of your python file. sys.argv[0] is what you're looking for. – Anonymous1847 Jul 21 '20 at 1:08
GET Parent Directory Path and make New directory (name new_dir)
Jay Patel
Jay Patel 24.3k●1212 gold badges●6565 silver badges●7474 bronze badges
Arindam Roychowdhury
Arindam Roychowdhury 4,065●55 gold badges●4444 silver badges●5252 bronze badges
Patrick Hofman
145k●1919 gold badges●224224 silver badges●297297 bronze badges
import os
def parent_filedir(n):
return parent_filedir_iter(n, os.path.dirname(__file__))
def parent_filedir_iter(n, path):
n = int(n)
if n <= 1:
return path
return parent_filedir_iter(n - 1, os.path.dirname(path))
test_dir = os.path.abspath(parent_filedir(2))
fuyunliu
fuyunliu 5●22 bronze badges
The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:
MPA
MPA 1,462●11 gold badge●2121 silver badges●3838 bronze badges
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
2021 Stack Exchange, Inc. user contributions under cc by-sa
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Accept all cookies Customize settings
Come write articles for us and get featured
Learn and code with the best industry experts
Get access to ad-free content, doubt assistance and more!
Come and find your dream job with us
Выбрать язык
русский
азербайджанский
албанский
амхарский
арабский
армянский
африкаанс
баскский
белорусский
бенгальский
бирманский
болгарский
боснийский
валлийский
венгерский
вьетнамский
гавайский
галисийский
греческий
грузинский
гуджарати
датский
зулу
иврит
игбо
идиш
индонезийский
ирландский
исландский
испанский
итальянский
йоруба
казахский
каннада
каталанский
киргизский
китайский (традиционный)
китайский (упрощенный)
корейский
корсиканский
креольский (Гаити)
курманджи
кхмерский
кхоса
лаосский
латинский
латышский
литовский
люксембургский
македонский
малагасийский
малайский
малаялам
мальтийский
маори
маратхи
монгольский
немецкий
непальский
нидерландский
норвежский
ория
панджаби
персидский
польский
португальский
пушту
руанда
румынский
самоанский
себуанский
сербский
сесото
сингальский
синдхи
словацкий
словенский
сомалийский
суахили
суданский
таджикский
тайский
тамильский
татарский
телугу
турецкий
туркменский
узбекский
уйгурский
украинский
урду
филиппинский
финский
французский
фризский
хауса
хинди
хмонг
хорватский
чева
чешский
шведский
шона
шотландский (гэльский)
эсперанто
эстонский
яванский
японский
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this.
In the parent directory, we have a subdirectory, geeks.py file and in the subdirectory, we have a python file named temp.py, Now let’s try if we can import the geeks module in the parent directory from the temp.py file in the subdirectory.
geeks.py (module in the parent directory)
print("This method in geeks module.......bye")
temp.py (python file in sub directory)
As we have discussed earlier it is not possible to import a module from the parent directory, so this leads to an error something like this.
File “C:/Users/sai mohan pulamolu/Desktop/parentdirectory/subdirectory/temp.py”, line 2, in
from parentdirectory import geeks
ModuleNotFoundError: No module named ‘parentdirectory’
Now let’s learn how to import a module from the parent directory:
In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys.path, so will add the parent directory path to the sys.path.
For our work, we use three different approaches that are explained below with the help of examples.
Method1: Here we will use sys module and set the path directly to the required module.
Add the parent directory to the sys.path using the append() method. It is a built-in function of sys module that can be used with a path variable to add a specific path for interpreters to search. The following example shows how this can be done.
sys.path.append('../parentdirectory')
from parentdirectory.geeks import geek_method
Method 2: Here we will use sys module as well as the path module for getting the directory and set the path directly to the required module.
Parameter:
Path: A path-like object representing a file system path.
Return Type: This method returns a normalized version of the pathname path.
Firstly we will get the name of the directory where the temp.py file is presently using the path.path(__file__).abspath(), secondly add the directory to the sys.path.append to check, we will use its method.
directory = path.path(__file__).abspath()
sys.path.append(directory.parent.parent)
from parentdirectory.geeks import geek_method
Method 3: Here we will use sys module as well as the os module for getting the directory (current as well as parent) and set the path directly to the required module.
Parameter:
path: A path-like object representing a file system path.
Return Type: This method returns a string value which represents the directory name from the specified path.
Firstly we will get the current directory by using the os.path.dirname(os.path.realpath(__file__)), secondly, we will get the parent directory by using the os.path.dirname(), finally, add the parent directory to the sys.path to check, we will use its method.
# getting the name of the directory
current = os.path.dirname(os.path.realpath(__file__))
# Getting the parent directory name
# where the current directory is present.
# now we can import the module in the parent
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course
Python - Import from sibling directory
Python – Import module from different directory
Python - Import module outside directory
Get parent of current directory using Python
Copy the entire contents of a directory to another directory in PHP
Shell Script to Delete a File from Every Directory Above the Present Working Directory
Why import star in Python is a bad idea
How to import a Python module given the full path?
Create and Import modules in Python
How to import JSON File in MongoDB using Python?
How to import an excel file into Python using Pandas?
How to import variables from another file in Python?
How to import a class from another file in Python ?
How to Import a CSV file into a SQLite database Table using Python?
How to import CSV file in SQLite database using Python ?
Import Modules From Another Folder in Python
How to import recharts.js library to ReactJS file ?
How to Import Custom Class in Java?
Difference between node.js require and ES6 import and export
Different ways to import csv file
Taboo Perverted Stories
Milf Like Big Dick
Xxx Porno Turkmen
Sissy Latex Porno
Hidden Voyeur Women Pissing
Python - Import from parent directory - GeeksforGeeks
Get parent of current directory using Python - GeeksforGeeks
PARENT_DIRECTORY — CMake 3.21.0 Documentation
How to Find a Parent Directory for a Web Site | Techwalla
CMake : parent directory? - Stack Overflow
Directory (computing) - Wikipedia
command line - Create file and its parent directory - Ask ...
Family Support Directory | Parent Club
Parent Directo Y











.jpg)








