Finding Current and File Directories in Python
When running Python scripts from the shell, it is often useful to know the current directory and the location of the executed Python file.
Current Directory:
To obtain the path to the current directory, use the os.getcwd() function:
import os current_directory = os.getcwd()
File Directory:
To determine the directory containing the Python file you are running, use the following code:
import os file_directory = os.path.dirname(os.path.realpath(__file__))
Note that __file__ is a constant that contains the absolute path to the current script. The os.path.realpath() function is used to resolve any symbolic links in the path.
Additional Notes:
The following modules, constants, and functions may be useful:
The above is the detailed content of How Can I Find the Current and File Directories in Python?. For more information, please follow other related articles on the PHP Chinese website!