Understand the absolute path and relative path in Python, and the absolute path in python
This article describes the absolute path strength and relative path in Python, shares it with you, and gives yourself some notes.
1. absolute path
OS. path. abspath ("file name "):
Displays the absolute path strength of a file.
Eg:
>>> import os>>> os.chdir("E:\\PycharmProjects\\odycmdb\\odycmdb")>>> os.listdir()['settings.py', 'urls.py', 'wsgi.py', '__init__.py', '__pycache__']>>> os.path.abspath("settings.py")'E:\\PycharmProjects\\odycmdb\\odycmdb\\settings.py'
2. Relative Path
OS. path. dirname ("file name "):
Displays the relative path of a file.
Eg:
>>> import os>>> os.chdir("E:\\PycharmProjects\\odycmdb\\odycmdb")>>> os.listdir()['settings.py', 'urls.py', 'wsgi.py', '__init__.py', '__pycache__']>>> os.path.dirname("settings.py")
3. Summary
Generally, absolute path functions and relative path functions are used together, especially before multiple file packages.
① OS. path. dirname (OS. path. abspath ("file name"): obtains the directory where the current folder is located.
Eg:
>>> import os>>> os.chdir("E:\\PycharmProjects\\odycmdb\\odycmdb")>>> os.listdir()['settings.py', 'urls.py', 'wsgi.py', '__init__.py', '__pycache__']>>> os.path.abspath("settings.py")'E:\\PycharmProjects\\odycmdb\\odycmdb\\settings.py'>>> os.path.dirname(os.path.abspath("settings.py"))'E:\\PycharmProjects\\odycmdb\\odycmdb'
② OS. path. dirname (OS. path. dirname (OS. path. abspath ("file name"): Get the directory on the top of the current folder
Eg:
>>> import os>>> os.chdir("E:\\PycharmProjects\\odycmdb\\odycmdb")>>> os.listdir()['settings.py', 'urls.py', 'wsgi.py', '__init__.py', '__pycache__']>>> os.path.abspath("settings.py")'E:\\PycharmProjects\\odycmdb\\odycmdb\\settings.py'>>> os.path.dirname(os.path.dirname(os.path.abspath("settings.py")))'E:\\PycharmProjects\\odycmdb'
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.