Get current working directory in Python

In this post, we are going to learn how to get current working directory in Python with examples. The python os module provides functions to handle the directory and files of the operating system. The os module is part of the standard library no installation is required for this. We can directly import into our program.

While working with files and directories we have to use two-path


  • Absolute path: It represents the location/path of files or directories starting from the root directory.
  • RelativePath: It is the path of the current working directory, starting from the current working directory.It is the directory in which our code or script is runnning.To get the current working directory os.getcwd() method used.

1. Get current working directory in python


The os module os.getcwd() method is used to get the absolute path of the working directory and returns it as a string.

Steps to get working directory


  • The first step is to Import the os module using “import os”
  • Use the os.getcwd() method to get current directory.
  • Printing Path using the print method.
  • To Find the location of script file we can use print(os.path.realpath(__file__))

Python Program to get current working directory

import os

cwdpath = os.getcwd()

print('Current Path :\n',cwdpath)
print(type(cwdpath))
print('Script path :\n',os.path.realpath(__file__))

Output

Current Path :
 C:\Users\Admin\Desktop\Python_program
 <class 'str'>
Script path :
 C:\Users\Admin\Desktop\Python_program\sample.py