[英]django os.path.dirname(__file__)
I am doing exercises from book: http://www.tangowithdjango.com/book17/chapters/templates_static.html 我正在从本书中进行练习: http : //www.tangowithdjango.com/book17/chapters/templates_static.html
and I have problem with this code: 我对此代码有疑问:
import os
print __file__
print os.path.dirname(__file__)
print os.path.dirname(os.path.dirname(__file__))
It shold print dir names. 它保留打印目录名称。 Instead of that it prints first line ( filename) but 2nd and 3rd line are also printed but empty.
取而代之的是,它打印第一行(文件名),但第二和第三行也打印但为空。
I get this behavior with Python 2.7 on Windows 7 and Ubuntu 14.04 我在Windows 7和Ubuntu 14.04上使用Python 2.7遇到了这种情况
EDIT: with this code i get absolute path with os.path.dirname(__file__)
: 编辑:使用此代码,我得到
os.path.dirname(__file__)
绝对路径:
import os
import django
import settings
print settings.BASE_DIR
What is the difference if the same code is imporeted from settings.py and coded directly? 如果从settings.py中伪造了相同的代码并直接进行编码,会有什么区别?
The __file__
value in the main script can be relative to the current working directory. 主脚本中的
__file__
值可以相对于当前工作目录。 Use os.path.abspath()
to make it absolute first: 使用
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__)))
This is the absolute path of the directory where the program resides which is what you want I believe. 我相信这是程序所在目录的绝对路径。
os.path.abspath(os.path.dirname(__file__))
This is the parent directory of the program 这是程序的父目录
os.path.join(os.path.dirname(__file__), 'some_directory')
This is the abbreviated directory where the program resides 这是程序所在的缩写目录
os.path.dirname(os.path.realpath(__file__))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.