Get Directory of Current .py File

Advertisement

Advertisement

Introduction

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.

Get .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 .py file

To get the full absolute path of the current .py file:

# 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 .py file

To get the directory name of the .py file:

# 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

Conclusion

After reading this you should understand how to get the full absolute path of any .py file and how to get just the path of the directory.

References

Advertisement

Advertisement