There are two types of paths: relative path and absolute path. For a Unix-like system, the absolute path is the path starting. A relative path is a path that does not start with a slash.
In fact, there is only one path in the operating system, that is, the absolute path. Relative Path, onlyProgramHelp us change it to an absolute path.
The program running in the operating system uses environment variables to generate relative paths as absolute paths for us. The getcwd () function is used to obtain the current working path of the current process. That is, the starting point of the relative path.
In python, you can use the OS. chdir function to switch the current working path.
The current working path is the path where the program is executed. The directory in which the program is executed and the current path is in which directory.
We often need to execute some files under the source code directory in Python. For example, we may need to use eval to dynamically execute a Python source file. Or copy some configuration files to the path of the target system. At this time, we cannot know the absolute path of these files, because we cannot predict which directory the user will install our program.
We cannot depend on the current working path. Because the user may not execute our program in our source code directory.
Then, how can we get the absolute path of the files under the source code directory?
I did this:
Abspath = none
If _ name _ = '_ main __':
Abspath = OS. Path. abspath (SYS. argv [0])
Abspath = OS. Path. dirname (abspath) + "/"
Print abspath
By getting the absolute path of the first parameter, we know the absolute path of the program, we can use the global variable abspath to assemble the absolute path of any file in the source code directory!