Get directory of current Python script
While working with file handling you might have noticed that files are referenced only by their names, e.g. ‘GFG.txt’ and if the file is not located in the directory of the script, Python raises an error. So, How is it done?
The concept of Current Working Directory (CWD) becomes important here. Consider the CWD as the folder, the Python is operating inside. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD.
Note: Folder where the Python script is running is known as Current Directory. This is not the path where the Python script is located.
Getting current working directory
Python provides OS module for interacting with the operating system. This module comes under Python’s standard utility module. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
To get the location of the current working directory os.getcwd() is used.
Parameter: No parameter is required.
Return Value: This method returns a string which represents the current working directory.
Note: To know more about os.getcwd() click here.
Getting the path of script
os.path.realpath() can be used to get the path of the current Python script. Actually os.path.realpath() method in Python is used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path. A special variable __file__ is passed to the realpath() method to get the path of the Python script.
Note: __file__ is the pathname of the file from which the module was loaded if it was loaded from a file.
path: A path-like object representing the file system path.
A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string value which represents the canonical path.
Note: To know more about os.path.realpath() click here.
Last Updated on March 17, 2022 by admin