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

╄→尐↘猪︶ㄣ 提交于 2020-07-31 06:32:06

问题


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

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:


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

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.

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

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a 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.



来源:https://stackoverflow.com/questions/38412495/difference-between-os-path-dirnameos-path-abspath-file-and-os-path-dirnam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!