我是 Django 项目的初学者。 Django 项目的 settings.py 文件包含这两行:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
我想知道两者的区别,因为我认为两者都指向同一个目录。如果您能提供一些链接 os.path 函数,这也会有很大的帮助。
最佳答案
BASE_DIR
指向PROJECT_ROOT
的parent 目录。您可以将这两个定义重写为:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
因为 os.path.dirname()
function简单地删除路径的最后一段。
在上面,__file__
名称指向当前模块的文件名,参见Python datamodel :
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file.
但是,它可以是相对 路径,所以os.path.abspath()
function用于将其转换为绝对路径,然后仅删除文件名并将模块所在目录的完整路径存储在 PROJECT_ROOT
中。
关于python - os.path.dirname(os.path.abspath(__file__)) 和 os.path.dirname(__file__) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38412495/