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

为何Python脚本中__file__输出的路径有的用斜杠有的用反斜杠?

解决Python模块中__file__路径格式不一致的问题

环境说明

  • 开发环境:PyCharm 2017.3(教育版)
  • Python版本:3.6.4

原代码与问题现象

你有两个脚本文件:

  1. modulesTut1.py(主执行文件)
import modulesTut2
print(__file__)
  1. modulesTut2.py(被导入的模块)
def f():
    print("f1")
print(__file__)
v = [1, 2, 3, 4, 5]

运行modulesTut1.py后,输出的路径格式出现明显差异:

C:\Users\shashank\PycharmProjects\python_rest\modulesTut2.py
C:/Users/shashank/PycharmProjects/python_rest/modulesTuts1.py

可以看到,被导入模块打印的是Windows标准的反斜杠路径,而主执行文件打印的是正斜杠路径,这种格式差异会给后续基于路径的文件操作带来潜在兼容性问题。

解决方案

在两个文件中打印__file__之前,先通过os.path.abspath()处理路径,统一输出格式。注意要先导入os模块:

修改后的modulesTut2.py:

import os

def f():
    print("f1")

# 统一路径格式
__file__ = os.path.abspath(__file__)
print(__file__)
v = [1, 2, 3, 4, 5]

修改后的modulesTut1.py:

import os
import modulesTut2

# 统一路径格式
__file__ = os.path.abspath(__file__)
print(__file__)

原理说明

os.path.abspath()函数会将输入的路径转换为当前系统下的标准绝对路径,自动适配系统的路径分隔符(Windows下为\,Linux/macOS下为/),从而彻底解决不同文件中__file__输出格式不一致的问题。

内容的提问来源于stack exchange,提问作者Shashank Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:24:42