You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spyder(Anaconda)中获取当前.py文件的路径?

How to Automatically Retrieve the Current Python Script's Directory (No Hardcoding Needed)

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__).parent directly gives you the script's parent directory.
  • resolve() converts the path to an absolute one, eliminating any relative path ambiguities.
  • The / operator works like os.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:55:19