The following path introduces the expression of the following path when opening a file in a py file written for windows:
open('aaa.txt')open('/data/bbb.txt')open('D:\user\ccc.txt')
Among these three expressions, the first two are relative paths, and the third is absolute paths. The absolute path is easier to understand, it is the most complete path, the relative of the relative path is the incomplete path, this relative refers to the path relative to the current folder, in fact, it is the folder path where the py file you wrote! That is to say, the relative path you write must be the file a in the current folder A or the file in the folder B in A to be open.
Suppose the current location of the py folder is: D:\user\public
Then the paths of the files opened by the three lines of code are:
D:\user\public\aaa.txt
D:\user\public\data\bbb.txt
D:\user\private\ccc.txt
It is easy to understand that when you want to open the file where the py file is located, you only need to use the relative path, and to use other folders, you need to use the absolute path.
Note: We often use'/' to denote relative paths, and'' to denote absolute paths. The \ in the above path means escape. If you don't understand, you can Baidu by yourself.
In addition, web URLs and linux and unix systems generally use'/'
Of course, we can also get the absolute path of the current folder, as follows:
importos
path1=os.path.abspath('.')#Represents the absolute path of the current folder
path2=os.path.abspath('..')#Represents the absolute path of the upper level folder of the current folder
Therefore, we often set a path1 global variable to represent the current absolute path, plus a relative path to open the file that needs to be opened. This is done to avoid conflicts on different platforms, because different platforms represent the relative path There is a difference.
Knowledge point expansion:
1、 Absolute path
os.path.abspath("file name"):
Shows the absolute path strength of a file
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"):
Shows the relative path of a file
import os
os.chdir("E:\PycharmProjects\odycmdb\odycmdb")
os.listdir()['settings.py','urls.py','wsgi.py','__init__.py','__pycache__']
os.path.dirname("settings.py")
So far, this article on how to express the relative path in python is introduced. For more related python relative path writing content, please search for ZaLou.Cn's previous articles or continue to browse the related articles below. I hope you will support ZaLou more in the future. Cn!
Recommended Posts