The use of OS. path in Python
1. Basic Knowledge
OS. path plays a very important role in setting the file path in different environments. We often see it in Django or Flask. The following methods are commonly used:
| Common Methods |
Function |
| OS. path. dirname (_ file __) |
Return the execution path of the current python execution script (see the example below). Here _ file _ is a fixed parameter. |
| OS. path. abspath (file) |
Returns the absolute path of a file in the current environment. Here, file is a parameter. |
| OS. path. join (basedir, file) |
Set the file path to the path where basedir is located. Both fbasedir and file are parameters. |
OK. Let's take a look at the example below.
2. Test
Let's take a look at two python script files in my current environment:
xpleaf@leaf:~/Source_Code$pwd/home/xpleaf/Source_Codexpleaf@leaf:~/Source_Code$lshello.pytest_os_path.py
There is no content in hello. py, which will be used for testing later. Let's take a look at the code of test_ OS _path.py:
importospath1=os.path.dirname(__file__)print'Thepath1is:',path1path2=os.path.abspath(path1)print'Thepath2is:',path2path3=os.path.join(path2,'hello.py')print'Thepath3is:',path3
By looking at the following two execution methods, we can deeply understand the functions of the above three methods:
(1) execute test_ OS _path.py in relative paths
xpleaf@leaf:~/Source_Code$pythontest_os_path.pyThepath1is:Thepath2is:/home/xpleaf/Source_CodeThepath3is:/home/xpleaf/Source_Code/hello.py
(2) execute test_ OS _path.py in absolute path mode.
xpleaf@leaf:~/Source_Code$python/home/xpleaf/Source_Code/test_os_path.pyThepath1is:/home/xpleaf/Source_CodeThepath2is:/home/xpleaf/Source_CodeThepath3is:/home/xpleaf/Source_Code/hello.py
Through the output of the above two execution methods, it is easy to see the role of the three. What is the purpose of actual development?
3. Use OS. path in actual development
In actual development, we must set the path of some files, for example, in Web development, the path settings for templates and static files, in fact, if you have used Django or Flask, you can often see that there are OS in their configuration files. the emergence of path is generally used as follows:
(1) first obtain the path of the current file (such as the configuration file)
basedir=os.path.abspath(os.path.dirname(__file__))
(2) set the absolute path of a file
static_file_path=os.path.join(basedir,'index.html')
Of course, OS. there are still many other ways to use path. Here we only list the three commonly used methods and provide general usage of the development environment. Whether or not this is necessary depends on everyone's own ideas and methods, here is only for reference.