Relative Paths in Python
When working with files and directories in Python, it's often necessary to specify paths relative to the current working directory. However, there are instances where you may need to specify relative paths from the location of your script file.
Question: Is there a way to define a relative path from the location of the script file, instead of the current working directory?
Answer:
Yes, you can use the following approach to obtain the absolute path from the location of the script file:
import os # Get the directory name of the current script file dirname = os.path.dirname(__file__) # Construct the absolute path by joining the directory name with the relative path filename = os.path.join(dirname, 'relative/path/to/file/you/want')
Explanation:
The above is the detailed content of How to Specify Relative Paths from a Python Script's Location?. For more information, please follow other related articles on the PHP Chinese website!