Getting the directory on which work is currently being done in a Python program is very essential. This can easily be achieved using the os.getcwd()
.
The Python scripting language comes with a lot of built in modules which make writing python much easier and fun nonetheless. One of such inbuilt modules is the OS module.
The OS module makes available different functions that are used to communicate with the operating system. This module is part of Python’s standard utility modules.
The os.getcwd()
method is one of the functions which the OS module provides.
The os.getcwd() method
is used to get the current working directory of a process.
Somewhere in your script, you can add this function anytime you wish to know or get the directory of an operation currently being carried out.
os.getcwd()
This function takes no parameters.
Returns a string which stands for the current working directory. This can be saved in a variable and accessed when needed.
# This program will return the CWD# The os module is imported to enable use of os methodsimport os#This line gets the current working directory (CWD)directory = os.getcwd()# Output the current working directory (CWD) to screenprint("The Current working directory is :", directory)
You can see from the output of the code above, the current directory of the code widget on this site was returned and printed to the output. This was achieved by:
os
module so as to make its method available for use.getcwd
method of the os
module and saving the return value which is the current working directory in a variable directory
on line 8.directory
to display.