Python os.path.dirname(os.path.abspath(__file__)) 和 os.path.dirname(__file__) 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38412495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:46:07  来源:igfitidea点击:

Difference between os.path.dirname(os.path.abspath(__file__)) and os.path.dirname(__file__)

pythondjangoos.path

提问by Rishabh Agrahari

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

我是 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__))

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.

我想知道区别,因为我认为两者都指向同一个目录。如果您可以提供一些链接 os.path 函数,那也会有很大帮助。

回答by Martijn Pieters

BASE_DIRis pointing to the parentdirectory 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()functionsimply 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__name指向当前模块的文件名,参见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 relativepath, so the os.path.abspath()functionis 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