os module of python built-in module

The function of the os module: the os module provides a very rich way to handle files and directories (manage and maintain directories and files).

The function of the os.path module: it is mainly used to obtain the attributes of the file (the (physical address) of the management path).

Xiao Sheng summarized some common attributes and functions.

Properties:

1.name: returns the kernel version of the operating system currently in use; output nt under windows system environment

2.environ: returns all environment variables and their contents in the current operating system, and stores and manages them in the form of key value pairs (stored in environ)

3.environ.get('environment variable name '): get the content of an environment variable and return it as a string

1 print(os.name)
2 
3 print(os.environ)
4 
5 print(os.environ.get('path'))

Path problem (concept):

Absolute path: called completion path; a string of physical addresses (string type), characteristics: with drive letter.

Relative path: the concept of relative. Take a certain position as a reference to get the relevant path, which is understood as the relative path. Differentiation: without the drive letter function.

Function:

1.getcwd(): returns the absolute path (describing the physical address in string format) of the file currently being executed

2.listdir(; path): save the subdirectory name and file name under the path path to the list as string type, and return [note] without indirect sub content

Create directory:

3.mkdir(path): create a single-layer directory instead of cascading directories

4.makedirs(path): create multi-level directory or single-level directory

[note] if a directory with the same name already exists in the path, continue to click create and an error will be reported: FileExistsError. For mkdir(): only one level of directories can be created at a time, and directories cannot be created in batch (cascade); an error will be reported: FileNotFoundError

Delete directory:

5.rmdir(path): delete single-layer directory, can't cascade delete directory

6. Removediers (path): delete multi-level directory or single level directory

Delete file:

7.remove(path): delete files

8.rename(src,dest): Rename directory or file

[note]: there are risks in deleting operation, so you need to be careful when using it!!! Because I don't go to the recycle bin

 1 print(os.getcwd())                        # Get current directory
 2  
 3 print(os.listdir(r'C:\Users\admin'))      # List the subdirectory name and file name under the current directory
 4  
 5 os.mkdir(r'D:\python\project\hello1')     # Create directory
 6  
 7 os.mkdir(r'aa')                           # Create directory aa
 8   
 9 os.mkdir(r'bb\cc\dd')                     # display FileNotFoundError Error type, cannot cascade to create directory
10  
11 os.makedirs(r'bb\cc\dd')                  # Create cascading directory
12   
13 os.rmdir(r'D:\python\project\hello1')     # delete hello1 Catalog
14  
15 os.rmdir(r'aa')                           # delete aa Catalog
16  
17 os.rmdir(r'bb\cc\dd\ee')                  # delete ee Catalog
18  
19 os.removedirs(r'bb\cc\dd')                # Cascading deletion bb\cc\dd
20  
21 os.removedirs(r'D:\python\project\hello') # Deleting single layer hello
22  
23 os.remove(r'abc.html')                    # Delete files
24 
25 os.rename(r'aa.html',r'bb.html')          # Under the relative path, the file name is aa.html Change to bb.html
26 
27 os.rename(r'D:\python\project\note.txt',r'D:\python\project\note.txt')   # Under absolute path, put the file name note Change to notes

Use of path module under os module:

1.join(first,second): splice the two parts (string data) of first and second to get a new string (describing the physical address), (not paying attention to whether the path actually exists)

2.getsize(path): returns the amount of bytes contained in the path path (locked to the file level)

3.exists(path): judge whether the physical path described by path really exists; if it exists, return True; otherwise, return False

4.isfile(path): judge whether the physical path described by path is a file; if it exists, return True; otherwise, return False (including the role of exists)

5.isdir(path): judge whether the physical path described by path is a directory; if it exists, return True; otherwise, return False (including the role of exists)

6.dirname(path): returns the part (string) before the last \ in the path, and finally returns in the form of string

7.basename(path): returns the part (string) following the last \ in the path, and finally returns in the form of a string

8.split(path): put the part (string) before the last \ in path variable into the first element bit of Yuanzu; put the part (string) after the last \ in path variable into the second element bit of Yuanzu; finally return the Yuanzu object

9.splitext(path): put the last. Preceding part (string) of path variable into the first element bit of Yuanzu; put the last. And the following part (string) of path variable into the second element bit of Yuanzu; finally return the Yuanzu object

10.realpath(path): returns the real path of path

11.abspath(path): returns the absolute path

[note] what os.path.abspath() gets is not the real path. Its function is to add the absolute path of the current working directory before the given file name. It doesn't care whether the file corresponding to the given file name really exists (because you may want to create a file)


1
import os
2
3 print(os.path.join(r'D:\python\project','1.txt')) # Synthesize directory and filename into one path D:\python\project\1.txt 4 5 print(os.path.getsize(r'D:\python\project\123.png')) # 54 6 print(os.path.getsize(r'D:\python\project')) # 24576 7 8 path = r'D:\python\project\note.txt' 9 10 print(os.path.exists(path)) 11 print(os.path.isfile(path)) 12 print(os.path.isdir(path)) 13 14 str1 = os.path.dirname(path) 15 print(str1,type(str1)) # Return to directory path D:\python\project <class 'str'> 16 17 str2 = os.path.basename(path) 18 print(str2,type(str2)) # Return file name note.txt <class 'str'> 19 20 tp1 = os.path.split(path) 21 print(tp1,type(tp1)) # Split file name and path ('D:\\python\\project','note.txt') <class 'tuple'> 22 23 tp2 = os.path.splitext(path) 24 print(tp2,type(tp2)) # ('D:\\python\\project\\note','.txt') <class 'tuple'>
1 import os
2  
3 os.path.realpath("b/1.txt")    # '/root/a/1.txt'
4 
5 # Hypothesis 1.jpg The path is D:\images\1.jpg, among D: \code Is my current working directory
6 file='1.jpg'
7 print(os.path.abspath(file))   # output D:\code\img1.jpg

Keywords: Python Windows

Added by vanzkee on Mon, 24 Feb 2020 13:53:04 +0200