Get Directory of Current .py File
source link: https://www.devdungeon.com/content/get-directory-current-py-file
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK