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

使用Path(__file__).parent获取父目录异常问题求助

解决Path(file).parent返回错误目录的问题
  • 先排查__file__的实际值:在代码中加入print(repr(__file__)),确认输出是否为'C:\\dir\\pythonfile.py'。如果不是,说明__file__本身不是完整的绝对路径,这会导致后续路径解析出错。
  • 强制使用绝对路径解析:
    用absolute()方法确保路径转为绝对路径后再获取父目录,代码示例:
    from pathlib import Path
    
    script_path = Path(__file__).absolute()
    parent_dir = script_path.parent
    print(parent_dir)  # 预期输出C:\dir
    
    或者使用resolve()并加上strict=True(强制验证文件存在,避免解析异常):
    parent_dir = Path(__file__).resolve(strict=True).parent
    
  • 排除特殊场景:
    • 若脚本被当作模块导入,检查__file__是否指向缓存的.pyc文件(不过这种情况parent仍应为C:\dir)。
    • 确认未在交互式Python环境中执行代码(该环境下__file__未定义,会直接报错)。

内容的提问来源于stack exchange,提问作者Sasha Alexander

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:49:58