os.path.dirname(os.path.abspath(__file__))和os.path.dirname(__file__)之间的差异

时间:2022-02-24 13:20:53

I am a beginner working on Django Project. Settings.py file of a Django project contains these two lines:

我是Django项目的初学者。设置。Django项目的py文件包含以下两行:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

I want to know the difference as I think both are pointing to the same directory. Also it would be great help if you could provide some links os.path functions.

我想知道它们的区别,因为我认为它们指向同一个目录。如果你能提供一些链接,这将是非常好的帮助。路径的功能。

1 个解决方案

#1


14  

BASE_DIR is pointing to the parent directory of PROJECT_ROOT. You can re-write the two definitions as:

BASE_DIR指向PROJECT_ROOT的父目录。您可以将这两个定义重写为:

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)

because the os.path.dirname() function simply removes the last segment of a path.

因为os.path.dirname()函数只删除路径的最后一部分。

In the above, the __file__ name points to the filename of the current module, see the Python datamodel:

在上面,__file__名称指向当前模块的文件名,请参见Python数据模型:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

__file__是加载模块的文件的路径名,如果它是从文件中加载的。

However, it can be a relative path, so the os.path.abspath() function is used to turn that into an absolute path before removing just the filename and storing the full path to the directory the module lives in in PROJECT_ROOT.

但是,它可以是一个相对路径,因此可以使用os.path.abspath()函数将其转换为一个绝对路径,然后删除文件名并存储模块在PROJECT_ROOT中的目录的完整路径。

#1


14  

BASE_DIR is pointing to the parent directory of PROJECT_ROOT. You can re-write the two definitions as:

BASE_DIR指向PROJECT_ROOT的父目录。您可以将这两个定义重写为:

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)

because the os.path.dirname() function simply removes the last segment of a path.

因为os.path.dirname()函数只删除路径的最后一部分。

In the above, the __file__ name points to the filename of the current module, see the Python datamodel:

在上面,__file__名称指向当前模块的文件名,请参见Python数据模型:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

__file__是加载模块的文件的路径名,如果它是从文件中加载的。

However, it can be a relative path, so the os.path.abspath() function is used to turn that into an absolute path before removing just the filename and storing the full path to the directory the module lives in in PROJECT_ROOT.

但是,它可以是一个相对路径,因此可以使用os.path.abspath()函数将其转换为一个绝对路径,然后删除文件名并存储模块在PROJECT_ROOT中的目录的完整路径。