Python: Get the path and name of the file that is currently executing
File Path and Name Finder
Write a Python program to retrieve the path and name of the file currently being executed.
Sample Solution:
Python Code:
# Import the 'os' module to work with the operating system.
import os
# Use the 'os.path.realpath(__file__)' to get the full path of the current Python script.
# This will print the path of the current file.
print("Current File Name: ", os.path.realpath(__file__))
Sample Output:
Current File Name : /home/students/fb6e28e0-2425-11e7-807b-bd9de91b1602.py
Explanation:
The ‘OS’ module provides a portable way of using operating system dependent functionality. The realpath() function returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).
If a path doesn’t exist or a symlink loop is encountered, and strict is True, OSError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists.
The above Python code imports the ‘os’ module and then calls its path sub-module's realpath function to get the full path of the current script file. The code then uses the print function to output the string "Current File Name : " followed by the full path of the script file to the console output.
Flowchart:
Python Code Editor:
Previous: Write a python program to call an external command in Python.
Next: Write a Python program to find out the number of CPUs using.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics