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 byos.getcwd()) wasC:\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 toC:\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 exactlyC:\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 fromC:\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 atC:\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
相关产品推荐
相关产品推荐

