Python os.getcwd() method

Usage

The os.getcwd() method, short for “get current working directory”, returns the absolute path of the current working directory (CWD) as a string.

This method is analogous to the pwd command in Unix-based systems (like Linux and macOS) or cd command (without arguments) in Windows.

Syntax

os.getcwd()

Return Value

os.getcwd() returns a string that represents the absolute path of the current working directory.

The os module in Python, including its getcwd() function, offers cross-platform compatibility with Windows, Linux, and macOS, ensuring the current working directory is returned in a system-appropriate format. Specifically, it uses backslashes \ as directory separators on Windows and forward slashes / on Unix-like systems.

Basic Example

The code snippet below prints the current working directory of the Python process:

import os

# Get the current working directory
current_directory = os.getcwd()
print("Current Working Directory:", current_directory)

# Output:
# Windows: "C:\Users\YourUserName\Documents\PythonProjects"
# Linux/macOS: "/home/yourusername/myproject"