os.getcwd() method returns the path of the current working directory. The current working directory is the folder from which the Python program is currently running or accessing files.
Example: In the code below, we get and display the current working directory.
import os
print(os.getcwd())
Output
C:\Users\gfg0753\AppData\Local\Programs\Microsoft VS Code
Explanation: os.getcwd() returns the path of the current working directory as a string.
Syntax
os.getcwd()
Returns a string representing the current working directory.
Examples
Example 1: In the code below, we store the current working directory in a variable and print it.
import os
cwd = os.getcwd()
print("Current Directory:", cwd)
Output
Current Directory: C:\Users\gfg0753\AppData\Local\Programs\Microsoft VS Code
Explanation: os.getcwd() returns the current directory path, which is stored in cwd.
Example 2: In the code below, we check whether the current directory path contains the folder name "Projects".
import os
cwd = os.getcwd()
print("Projects" in cwd)
Output
False
Explanation: "Projects" in cwd checks whether the folder name exists in the path returned by os.getcwd().
Example 3: In the code below, we extract and display only the name of the current directory.
import os
cwd = os.getcwd()
print(os.path.basename(cwd))
Output
Microsoft VS Code
Explanation: os.path.basename(cwd) extracts the last folder name from the path returned by os.getcwd().