getcwd() method - Get Current Working Directory in Python using the os module

The getcwd() method of the os module in Python, returns the current working directory of the process. The Python example, creates a file in the working directory only by using the file name and prints the whole path. The example also creates a directory and changes the working directory of the process to the newly created directory.

Os Updated 16 Nov 2018 1 min read

Method Name

os.getcwd

Method signature

os.getcwd()

Return Value

None

Overview

  • The method os.getcwd() in Python returns the current working directory of a process.
  • Every process running under an operating system has an associated working directory, which is called as the current working directory of the process.
  • The current working directory of a process can be changed by calling the Python method os.chdir().
  • While referring to any file, only the file names or paths relative to the current working directory can be used instead of using absolute paths.

Example

python
import os

# Get the current working directory

print("The current working directory is:")

print(os.getcwd())

# Create a file without specifying any path

# so as to create the file in the current working directory

fileName = "Contents.txt"

fileObject = open(fileName, "w+")

# Print the full path of the newly created file now

print("Full path of the created file is:")

print(os.path.realpath(fileName))

# Now create a new directory

os.mkdir('NewDirectory')

# Change the working directory to the newly created directory

os.chdir('NewDirectory')

# Print the current working directory

print("Current working directory after changing it:")

print(os.getcwd())

Output

Output
The current working directory is:

/Users/Python

Full path of the created file is:

/Users/Python/Contents.txt

Current working directory after changing it:

/Users/Python/NewDirectory