Get/Display Current Working Directory In Python

Python provides different ways and methods in order to get or display the current working directory. The current working directory is used to specify the active path which is used if some file is created or read without an absolute path. The current working directory also shortened as cwd.

Get/Display Current Working Directory with os.getcwd() Method

The os module prvides the getcwd() method. The cwd means “current working directory”. The os module should be importedto call getcwd() method. The getcwd() method do not require any parameter and returns the current working directory.

import os


Alternatively the current working directory can be set into a variable. This variable can be used later or provided single or more methods as parameter. In the following example we will set the current working directory or cwd into the variable named cwd.

import os



Get/Display Current Working Directory with os.getcwd() Method

The pathlib module provides the cwd() method. The cwd() method can be used to get current working directory via pathlib.Path.cwd().

import pathlib


Alternatively the Path can be imported like below.

from pathlib import Path


Change Current Working Directory

The os module also provides the method named realpath(). The realpath() method returns the provided absoulte paths complete path or real path. This method also accepts Linux bash commands where the “.” is used to express curent working directory.

import os


Leave a Comment