Search code examples
python-3.ximportpath

Return the name of the directory that is located just above the current working directory in Python using the os module


I am trying to solve this but is showing me an error, on Python documentation I was trying to find more about the absolute path, and I am not sure if something else is wrong here, thanks in advance. (Sorry I am not sure how to fit the code in the code block part).

import os

def parent_directory():

    # Create a relative path to the parent 
    # of the current working directory 

    relative_parent = os.chdir("..")

    # Return the absolute path of the parent directory
    return os.path.abspath(relative_parent)

print(parent_directory())

Solution

  • This will do the job:

    import os
    
    def parent_directory():
      relative_parent = os.path.dirname(os.getcwd())
      os.chdir(relative_parent)
      return(os.getcwd())
    
    print(parent_directory())
    

    Suppose the .py file is located in this path:

    /home/folderA/folderB/getParentDir.py
    

    the returned result shall be:

    /home/folderA/