【问题标题】:os.path.dirname returning empty string in djangoos.path.dirname 在 django 中返回空字符串
【发布时间】:2015-07-19 05:16:03
【问题描述】:

我是 python django 框架的新手,我不太明白为什么

os.path.dirname(__file__)

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

返回一个空字符串。

我的文件夹结构如下:

djangoWorkspace/
  tangoWithDjangoProject/
     rango/
     tangoWithDjangoProject/
          settings.py

Settings.py 包含目录名的代码。

【问题讨论】:

  • 我看到了,但它没有回答我的问题。
  • Python 和 Django 版本是什么?
  • python 是 2.7.6,django 是 1.7
  • settings.py中print __file__的输出是什么?

标签: python django path


【解决方案1】:

os.path.dirname(os.path.dirname(__file__)) 没有任何意义。您需要按照重复问题中的建议致电os.path.dirname(os.path.abspath(__file__))

结果为空,因为__file__ 仅包含 Python 文件的文件名。

os.path.dirname 不解析给定文件的位置,而只是从给定字符串中去除文件名。

os.path.dirname('../foo/bar/baz.txt')
Out[4]: '../foo/bar'

如您所见,路径尚未解析,bar.txt 已从字符串中删除。

你正在做的相当于:

__file__ = 'baz.txt'

os.path.dirname(__file__)
Out[6]: ''

您应该这样做:

os.path.dirname(os.path.abspath(__file__))
Out[10]: '/home/noxdafox/foo/bar'

【讨论】:

  • 我正在关注教程here,其中包含我在上面编写的代码。 django 库自动生成了该代码。
  • 出于某种原因,使用 os.path.abspath 不起作用,但 os.path.dirname 起作用。不知道为什么。你能解释一下吗?
  • 要明确:所有提到的方法都没有在 FS 中执行查找以找到给定字符串的正确位置。 os.path.abspath documentation 清楚地显示了函数如何尝试解析给定的路径。这是一个有根据的猜测,而不是可靠的搜索。为了更好地了解发生了什么,我宁愿打印 _file_ 内容和 os.getcwd 返回的值。
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多