Home >Backend Development >Python Tutorial >How Do I Get the Current Directory and File Location in Python?
Get Current Directory and File Location in Python
Determining the current directory and the location of the Python file being executed can be useful for various purposes. Here's how to achieve it:
1. Current Directory
To obtain the current working directory (where the Python script was executed from the shell), use the following Python code:
import os cwd = os.getcwd()
This will provide the absolute path to the current directory, even if a different directory was specified in the shell prior to running the Python script.
2. Python File Location
To get the full path to the directory where the Python file is stored, use this code within the file:
import os dir_path = os.path.dirname(os.path.realpath(__file__))
__file__ is a constant that represents the name of the currently executing Python file relative to the current working directory. os.path.dirname extracts the directory name from the provided path, while os.path.realpath ensures that any symbolic links in the path are resolved.
Additional Resources:
The above is the detailed content of How Do I Get the Current Directory and File Location in Python?. For more information, please follow other related articles on the PHP Chinese website!