When writing a Python application sometimes it can be useful to get the name of the Python file where the code is stored. To take it further, you might want to get the full absolute path of the Python file or just the directory of the Python file. This can be particularly useful if you want to reference resources relative to the Python file, wherever it may reside.
.py file name
To get the filename of the current python:
# Example file: /home/nanodano/test.py current_file_name = __file__ print(current_file_name) # Example output: test.py
Get full absolute path of
To get the full absolute path of the current
# Example file: /home/nanodano/test.py from os.path import abspath current_file_name = __file__ full_path = abspath(current_file_name) print(full_path) # Example output: /home/nanodano/test.py
Get the directory path only of
To get the directory name of the
# Example file: /home/nanodano/test.py from os.path import abspath, dirname file_directory = dirname(abspath(__file__)) print(file_directory) # Example output: /home/nanodano
Here is an example of a different way to write the same thing:
# Example file: /home/nanodano/test.py import os print(os.path.dirname(os.path.abspath(__file__))) # Example output: /home/nanodano
After reading this you should understand how to get the full absolute path
.py file and how to get just the path of the directory.