Find the Current Directory and File's Directory
Determining the current directory and the location of a Python script can be useful for various tasks. Here's a breakdown of how to achieve these in Python:
Current Directory:
-
getcwd(): This function returns the full path of the current working directory as a string.
Example:
import os
curr_dir = os.getcwd()
Copy after login
File's Directory:
-
os.path.realpath(__file__): This expression gets the full path to the directory containing the script. file holds the path of the executing Python file relative to the current working directory. os.path.realpath() resolves any symbolic links in the path.
Example:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
Copy after login
Note:
- If os.chdir() has been used to change the current working directory, __file__'s value will not be updated accordingly.
- For thorough documentation, refer to the os and os.path modules, os.getcwd(), __file__, os.path.realpath(), os.path.dirname(), and os.chdir().
The above is the detailed content of How Can I Find My Python Script's Directory and the Current Working Directory?. For more information, please follow other related articles on the PHP Chinese website!