Home >Backend Development >Python Tutorial >How Can I Get the Current Script's Filename and Path in Python?
Accessing Current Execution Path and Filename in Python
When executing multiple script files in a sequence, it becomes necessary to retrieve the filepath of the currently running script within the process. Consider the scenario where you have three linked scripts:
The objective is to determine the filename and path of script_3.py without passing it as an argument from script_2.py.
Solution:
A straightforward solution to retrieve the current script's path and filename is to utilize the file attribute. This attribute holds the path of the python file that is currently being executed. The code snippet below demonstrates its usage:
__file__
However, file may contain symbolic links. To remove these links and obtain the absolute path, the os.path.realpath function can be used:
import os os.path.realpath(__file__)
This method provides the absolute path of the currently executing script, making it a reliable solution for retrieving the necessary information from within the script itself.
The above is the detailed content of How Can I Get the Current Script's Filename and Path in Python?. For more information, please follow other related articles on the PHP Chinese website!