How to Retrieve the Filename of a Python File?

Estimated read time 1 min read

To retrieve the filename of a Python file within the script itself, you can make use of the __file__ attribute. The __file__ attribute holds the path of the current script file. Here’s an example:

import os

# Retrieve the filename of the Python file
filename = os.path.basename(__file__)

print(f"The filename is: {filename}")

In the code above:

  1. The os.path.basename() function is used to extract the filename from the file path stored in the __file__ attribute.
  2. The extracted filename is then stored in the filename variable.
  3. Finally, the filename is printed to the console.

When you run this code, it will display the filename of the Python script.

Note: The __file__ attribute may not behave as expected when used within an interactive environment or when the script is executed indirectly (e.g., using exec() or eval()). It is recommended to use this method in standalone Python files.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply