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.
Syntax: os.getcwd()
Parameter: No parameter is required.
Return Value: This method returns a string which represents the current working directory.
Example:
- Python3
# Python program to explain os.getcwd() method # importing os module import os # Get the current working # directory (CWD) cwd = os.getcwd() # Print the current working # directory (CWD) print ( "Current working directory:" ) print (cwd) |
Output:
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.
Syntax: os.path.realpath(path)
Parameter:
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.
Example:
- Python3
# Python program to get the # path of the script import os # Get the current working # directory (CWD) cwd = os.getcwd() print ( "Current Directory:" , cwd) # Get the directory of # script script = os.path.realpath(__file__) print ( "SCript path:" , script) |
Output:
Note: To know more about os.path.realpath() click here.
Last Updated on March 17, 2022 by admin