os module provides a very rich way to handle files and directories.
We are doing automated testing process, there are many paths the code; if the entire file is copied to another location, how to ensure the path in the code on another colleague's computer or can not change the path in different environments, dynamic access to directory path; this allows expansion and improve the maintainability of the code;
For example: Code automation project, we may need to: extract the configuration file location, Excel test data extraction position, the log reports the input file location, code execution results generated HTML reports location, entrance test files automatically identify the interface class. . Need to get the path dynamic directory or file; requires special files to store these paths, just import can obtain the corresponding absolute path;
1, how to get each file or directory absolute path, we have to practice in the implementation of test.py file
Example directory structure:
Code Exercise:
Import os # Import module os # 1, to obtain the absolute path of the current file test.py # Use path os module among the "abspath built-in variable __file__ get the absolute path of the current file path1 = os.path.abspath ( __file__ ) Print (path1) # 2, dirname can get the absolute path to a directory on the current path where --B absolute path to the folder path2 = os.path.dirname (path1) Print (path2) # 3, dirname can get a directory on the current path where the absolute path --A absolute path to the folder path3 = os.path.dirname (path2) Print (path3) # absolute path to get the file on the first comprehensive, re-use the two dirname can get to the root of the absolute path # Combined to write: get the absolute path to the root directory A_DIR = os.path.dirname (os.path.dirname (os.path.abspath ( __FILE__ ))) Print (A_DIR) # Using stitching to join the absolute path of the root directory of the + B B_DIR = the os.path.join (A_DIR, " B " ) Print (B_DIR) # Using stitching to join the absolute path of the root directory of C + The C_Dir = the os.path.join (A_DIR, " C " ) Print (The C_Dir) # Use join to splice C filename + aa.py absolute path aa_DIR = os.path.join (The C_Dir, " aa.py " ) Print (aa_DIR)
Code execution results:
******* Please respect the original, as to reprint, please indicate the source: Reprinted from: https://www.cnblogs.com/shouhu/ Thank you! ! *******