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 them into our program.
Path to create directories or File in Python
- Absolute path: It represents the location/path of files or directories starting from the root directory.
- Relative path: 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 running. To get the current working directory os.getcwd() method is used.
1. How to 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 a working directory in Python
- 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__))
Current Path : C:\Users\Admin\Desktop\Python_program <class 'str'> Script path : C:\Users\Admin\Desktop\Python_program\sample.py