Python os.getcwd() Method
os.getcwd() Overview
The os.getcwd() method is used to return the current working directory.
os.getcwd() Syntax
The syntax format of the getcwd() method is as follows.
os.getcwd()
os.getcwd() Parameters
- None
os.getcwd() Return Value
Returns the working directory of the current process.
os.getcwd() Demo#1
The following example demonstrates the use of the getcwd() method.
#!/usr/bin/python3
import os, sys
# Switch to the "/var/www/html" directory
os.chdir("/var/www/html" )
# Print the current directory
print ("Current working directory : %s" % os.getcwd())
# Open "/tmp"
fd = os.open( "/tmp", os.O_RDONLY )
# Use the os.fchdir() method to modify the directory
os.fchdir(fd)
# Print the current directory
print ("Current working directory : %s" % os.getcwd())
# Close file
os.close( fd )
Output:
Current working directory : /var/www/html
Current working directory : /tmp
os.getcwd() Demo#2
Using os.getcwd()
method to get current working directory
# Python program to explain os.getcwd() method in apidemos.com
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
print("Current working directory:", cwd)
Output:
Current working directory: C:\Users\Rajnish\AppData\Local\Programs\Python\Python37
os.getcwd() Demo#3
Using os.getcwd()
method to get current working directory of apidemos which is root
# Python program to explain os.getcwd() method in apidemos.com
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
# which is root in this case
print("Current working directory:", cwd)
Output:
Current working directory: /