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
Difference between os.path.dirname(os.path.abspath(__file__)) and os.path.dirname(__file__)
提问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_DIR
is 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
。