os.path.dirname(os.path.abspath(__file__)) 和 os.path.dirname(__file__) 之间的区别
Difference between os.path.dirname(os.path.abspath(__file__)) and os.path.dirname(__file__)
我是 Django 项目的初学者。
Settings.py Django 项目的文件包含这两行:
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
.
我是 Django 项目的初学者。 Settings.py Django 项目的文件包含这两行:
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
.