Hướng dẫn python get parent directory

An alternate solution of @kender

import os
os.path.dirname[os.path.normpath[yourpath]]

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:

import os
os.path.normpath[os.path.join[yourpath, os.pardir]]

Here the outputs for every case that can find [Input path is relative]:

os.path.dirname[os.path.normpath['a/b/']]          => 'a'
os.path.normpath[os.path.join['a/b/', os.pardir]]  => 'a'

os.path.dirname[os.path.normpath['a/b']]           => 'a'
os.path.normpath[os.path.join['a/b', os.pardir]]   => 'a'

os.path.dirname[os.path.normpath['a/']]            => ''
os.path.normpath[os.path.join['a/', os.pardir]]    => '.'

os.path.dirname[os.path.normpath['a']]             => ''
os.path.normpath[os.path.join['a', os.pardir]]     => '.'

os.path.dirname[os.path.normpath['.']]             => ''
os.path.normpath[os.path.join['.', os.pardir]]     => '..'

os.path.dirname[os.path.normpath['']]              => ''
os.path.normpath[os.path.join['', os.pardir]]      => '..'

os.path.dirname[os.path.normpath['..']]            => ''
os.path.normpath[os.path.join['..', os.pardir]]    => '../..'

Input path is absolute [Linux path]:

os.path.dirname[os.path.normpath['/a/b']]          => '/a'
os.path.normpath[os.path.join['/a/b', os.pardir]]  => '/a'

os.path.dirname[os.path.normpath['/a']]            => '/'
os.path.normpath[os.path.join['/a', os.pardir]]    => '/'

os.path.dirname[os.path.normpath['/']]             => '/'
os.path.normpath[os.path.join['/', os.pardir]]     => '/'

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In Python, OS module is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. 
    OS module provides various ways for getting the parent directory. Some of the ways are: 
     

    • Using os.path.abspath[] 
       
    • Using os.path.dirname[] 
       
    • Using os.path.relpath[] and os.path.dirname[] 
       

    Using os.path.abspath[]

    os.path.abspath[] can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs the help of os.path.join[] and os.pardir[]. 
    os.path.join[] method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator [‘/’] following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator [‘/’] is put at the end. 
     

    Syntax: os.path.abspath[path]
    Parameters: 
    path: A path-like object representing a file system path.
    Return Type: Returns a string that is a normalized version of the path. 
     

    Example:
     

    Python3

    import os

    path = os.getcwd[]

    print["Current Directory", path]

    print[os.path.abspath[os.path.join[path, os.pardir]]]

    Output: 
     

    Using os.path.dirname[]

    os.path.dirname[] method in Python is used to get the directory name from the specified path.
     

    Syntax: os.path.dirname[path]
    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. 
     

    Example: 
     

    Python3

    import os

    path = os.getcwd[]

    print["Current Directory", path]

    print[]

    parent = os.path.dirname[path]

    print["Parent directory", parent]

    Output:
     

    Using os.path.relpath[] and os.path.dirname[]

    In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using os.path.relpath[] and os.path.dirname[] together. 
    os.path.relpath[] method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.
     

    Syntax: os.path.relpath[path, start = os.curdir]
    Parameter: 
    path: A path-like object representing the file system path. 
    start [optional]: A path-like object representing the file system path. 
    The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.
    A path-like object is either a string or bytes object representing a path.
    Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222 
     

    Example:
    To get the parent directory according to levels specified by the user, we will create a function getParent[] which will take path and levels as arguments. Inside the function, a for loop will iterate level+1 numbers of time and os.path.dirname[] will be called inside the for loop. Calling this function inside the for loop will give us the starting point from which os.path.relpath[] will give the relative file path.
    Below is the implementation.
     

    Python3

    import os.path

    def getParent[path, levels = 1]:

        common = path

        for i in range[levels + 1]:

            common = os.path.dirname[common]

        return os.path.relpath[path, common]

    path = 'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'

    print[getParent[path, 2]]

    Output:
     


    Chủ Đề