【问题标题】:django os.path.dirname(__file__)django os.path.dirname(__file__)
【发布时间】:2015-01-25 10:44:53
【问题描述】:

我正在做书中的练习: http://www.tangowithdjango.com/book17/chapters/templates_static.html

我对这段代码有疑问:

import os

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

它保存打印目录名称。而不是打印第一行(文件名) 但第 2 和第 3 行也打印出来但为空。

我在 Windows 7 和 Ubuntu 14.04 上使用 Python 2.7 得到了这种行为

编辑:使用此代码,我得到os.path.dirname(__file__) 的绝对路径:

import os
import django
import settings

print settings.BASE_DIR

同样的代码从settings.py中导入,直接编码有什么区别?

【问题讨论】:

  • 你的答案都有效。我很感兴趣为什么书中只提到 os.path.dirname(file) 是错误还是有一些根本原因?

标签: python django operating-system


【解决方案1】:

主脚本中的__file__ 值可以相对于当前工作目录。首先使用os.path.abspath() 使其绝对化:

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

【讨论】:

    【解决方案2】:

    这是程序所在目录的绝对路径这是你想要的我相信。

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

    这是程序的父目录

    os.path.join(os.path.dirname(__file__), 'some_directory')
    

    这是程序所在的缩写目录

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

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2012-06-12
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多