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

Python中OS模块未返回预期路径问题求助

Fixing Your Path Retrieval Issue

First, let's break down why your current code isn't giving you the path you need:

  • Your script lives in C:\Users\zaidd\Documents\Treasure Hunt\1, but when you ran it, your current working directory (returned by os.getcwd()) was C:\Users\zaidd—that’s why your first split output shows ['C:', 'Users', 'zaidd'].
  • The line os.path.abspath(os.path.join(path, os.pardir)) takes that working directory and moves up one level to C:\Users, which aligns with your output.

The core problem here is that os.getcwd() returns the directory you executed the script from, not the directory where the script itself is stored. To reliably get the script’s containing folder (the exact path you want: C:\Users\zaidd\Documents\Treasure Hunt\1), you need to use the __file__ attribute instead.

Corrected Code

Here’s how to consistently retrieve your target path:

import os

# Get the full absolute path of your script file
script_full_path = os.path.abspath(__file__)
# Extract the directory containing the script (this is your desired path!)
target_directory = os.path.dirname(script_full_path)

print("Script location:", script_full_path)
print("Target path:", target_directory)

Key Explanations:

  • __file__ is a built-in attribute that holds the path to the current script file (either relative or absolute).
  • os.path.abspath(__file__) converts that path to a full absolute path to avoid any relative path confusion.
  • os.path.dirname() strips off the script filename from the full path, leaving you with exactly C:\Users\zaidd\Documents\Treasure Hunt\1.

Why Your Original Code Didn’t Work

A quick recap of the missteps:

  • os.getcwd() depends on where you run the script from, not where the script is saved. If you launch it from C:\Users\zaidd, that’s what it returns.
  • os.chdir(cwd) changes your working directory to the parent of the current working directory, which is why you ended up at C:\Users.

If you ever need to navigate relative to your script’s location (instead of the working directory), using __file__ is the most reliable approach.

内容的提问来源于stack exchange,提问作者Zaid Ahmad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:47:48