How do I get the full path of the current file's directory?
You can use the os module to get the full path of the current file's directory.
You can use the os module to get the full path of the current file's directory. The os.path module provides several useful functions for working with file paths.
In Python, __file__ is a module-level variable that contains the path of the current file. You can use the os.path.dirname() function to get the directory containing the current file, and then use os.path.abspath() to get the full path of that directory.
Get the full path of the current file's directory in Python
import os
current_file_directory = os.path.dirname(os.path.abspath(__file__))
print(current_file_directory)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use os.path.realpath, which follows symlinks (if any) and returns the actual location of the file on the filesystem.
Get the actual location of the file on the filesystem in Python
import os
current_file_directory = os.path.dirname(os.path.realpath(__file__))
print(current_file_directory)This will print the full path of the current file's directory to the console.
Modern alternative using pathlib (Python 3.4+)
from pathlib import Path
current_file_directory = str(Path(__file__).parent.resolve())
print(current_file_directory)