如何在Spyder(Anaconda)中获取当前.py文件的路径?
My Scenario
I have a script located at Users/path/to/my/script.py that I run locally. Right now, I'm manually defining a base path like this:
sub_path = 'Users/path/to/my/' os.chdir(sub_path + 'other_script/')
I want to replace the hardcoded sub_path with code that automatically gets the directory where script.py is stored, similar to how os.getcwd() works but focused on the script's location instead of my current working directory.
Solutions
Here are two robust methods to achieve this, depending on your Python version:
1. Traditional os.path Method (Works with All Python Versions)
Every script file has a special __file__ attribute that stores its path. We can use this with os.path utilities to get the script's directory:
import os # Get the absolute path of the current script full_script_path = os.path.abspath(__file__) # Extract the directory containing the script script_directory = os.path.dirname(full_script_path) # Now safely navigate to the subdirectory os.chdir(os.path.join(script_directory, 'other_script'))
os.path.abspath(__file__)ensures we get an absolute path, even if you run the script from a different folder.os.path.dirname()strips off the script's filename to leave you with its parent directory.- Using
os.path.join()is better than string concatenation because it handles path separators correctly (e.g.,/on macOS/Linux,\on Windows).
2. Modern pathlib Method (Python 3.4+)
If you're using Python 3.4 or later, the pathlib module provides a cleaner, object-oriented approach:
from pathlib import Path import os # Get the script's directory as a resolved (absolute) Path object script_directory = Path(__file__).parent.resolve() # Change directory to the subfolder os.chdir(script_directory / 'other_script')
Path(__file__).parentdirectly gives you the script's parent directory.resolve()converts the path to an absolute one, eliminating any relative path ambiguities.- The
/operator works likeos.path.join()for Path objects, making the code more readable.
Important Distinction from os.getcwd()
Remember: os.getcwd() returns the directory you ran the script from, not the directory where the script is saved. The methods above specifically target the script's actual location, which is exactly what you need here.
内容的提问来源于stack exchange,提问作者LucSpan

