【问题标题】:Get path for the file being run and not the dir of where the call is from [duplicate]获取正在运行的文件的路径,而不是调用来自的目录 [重复]
【发布时间】:2021-06-08 11:44:00
【问题描述】:

假设我有以下/home/my_user/files/path.py,其中包含print(os.getcwd()),我从/home/运行

python3 ./my_user/files/path.py

我得到了输出/home/。有没有办法打印正在运行的文件所在的文件夹,例如 /home/my_user/files 与文件的运行位置无关?

【问题讨论】:

    标签: python


    【解决方案1】:

    你需要获取文件的真实路径,而不是当前目录

    import os
    
    os.path.dirname(os.path.realpath(__file__))
    

    【讨论】:

      【解决方案2】:

      你想要的是 Python 文件的目录,而不是工作目录:

      import os.path
      
      print(os.path.dirname(__file__))
      

      【讨论】:

        【解决方案3】:

        这将为您提供执行的python文件目录的绝对路径

        os.path.dirname(os.path.abspath(__file__))
        

        【讨论】:

          猜你喜欢
          • 2020-03-19
          • 2013-12-18
          • 1970-01-01
          • 2012-07-21
          • 2020-10-20
          • 1970-01-01
          • 2022-12-14
          • 2018-05-31
          • 1970-01-01
          相关资源
          最近更新 更多