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:
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:
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 |