我正在从书中做练习: 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__))
它打印了dir名字。而不是它打印第一行(文件名) 但是第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得到相同的代码并直接编码,有什么区别?
答案 0 :(得分: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__)))
答案 1 :(得分:1)
这是程序所在目录的绝对路径这是你想要的我相信。
os.path.abspath(os.path.dirname(__file__))
这是程序的父目录
os.path.join(os.path.dirname(__file__), 'some_directory')
这是程序所在的缩写目录
os.path.dirname(os.path.realpath(__file__))