Python os.getcwd() Method



The Python getcwd() method stands for get current working directory. As the name suggests, it returns the current working directory of a process. When this method is invoked, it displays a string that represents the path of directory in which we are currently working on.

Syntax

The syntax for getcwd() method is shown below −

os.getcwd()

Parameters

The Python os.getcwd() method does not accept any parameter.

Return Value

The Python os.getcwd() method returns a string representing the path of current working directory.

Example

The following example shows the usage of getcwd() method. Here, we pass the return value to the print statement to display the result.

#!/usr/bin/python
import os, sys

# First go to the required directory
os.chdir("/home/tp/Python/tmp/new" )

# Then print current working directory
print ("Current working dir : %s" % os.getcwd())

When we run above program, it produces following result −

Current working dir : /home/tp/Python/tmp/new

Example

This example will change the current working directory to "/tmp" using "os.chdir()" method and then print the path of new working directory to verify the change.

#!/usr/bin/python
import os, sys

# First go to the desired directory
os.chdir("/home/tp/Python/tmp" )

# Print current working directory
print ("Current working dir : %s" % os.getcwd())

# Now open a directory "/home"
fd = os.open( "/home", os.O_RDONLY )

# Use os.fchdir() method to change the dir
os.fchdir(fd)

# Print current working directory
print ("Current working dir : %s" % os.getcwd())

# Close opened directory
os.close( fd )
print("Closed successfully!!")

On running, the above program will display the following result −

Current working dir : /home/tp/Python/tmp
Current working dir : /home
Closed successfully!!
python_files_io.htm
Advertisements