Explain os. mkdir and os. mkdirs in detail
- 2020-12-16 06:02:20
- OfStack
Create a directory
In Python, you can use the os.mkdir () function to create a directory (creating a level 1 directory).
The prototype is as follows:
os.mkdir(path)
The parameter path is the path to the directory to create.
For example, the directory where hello is to be created under the D disk
>>> import os
>>> os.mkdir('d:\hello')
You can use the os. makedirs () function to create multilevel directories.
The prototype is as follows:
os.makedirs(path)
The parameter path is the path to the directory to create.
For example, create books directory under D disk and books directory under book directory
>>> import os
>>>os.makedirs('d:\\books\\book')
Delete the directory
In Python, you can delete directories using the os.rmdir () function.
The prototype is as follows:
os.rmdir(path)
The parameter path is the path to the directory to be deleted.
For example, D disk hmm directory deleted
>>> import os
>>> os.rmdir('d:\hmm')
Delete multilevel directories
In Python, you can use the os.removedirs () function to remove multilevel directories.
The prototype is as follows:
os.removdirs(path)
The parameter path is the path to the multilevel directory to be deleted.
>>> import os
>>> os.removedirs('d:\\books\\book')
Note: the directory to be deleted must be an empty directory,
Delete the file
In Python, you can use the os.remove () function to delete a file (note that 1 must be 1 file).
The prototype is as follows:
os.remov(path)
The parameter path is the path to the file to be deleted.
For example, delete book. txt file in books directory under D disk
>>> import os
>>>os.remove('d:\\books\\book\\book.txt')
Directory traversal
In Python, you can use the os.walk () function to traverse the directory.
The prototype is as follows:
>>> import os
>>> os.mkdir('d:\hello')
0
Its parameter path is the directory to be traversed, traverses path, returns 1 object, each part of which is a 3 tuple (' directory x', [directory list under x], and files under x).
Such as:
>>> import os
>>> os.mkdir('d:\hello')
1
Determine if it is a directory
In Python, you can use the os.path.isdir () function to determine if a 1 path is a directory.
Its function prototype is as follows:
>>> import os
>>> os.mkdir('d:\hello')
2
Its parameter path is the path to be judged. Returns TRUE if yes, FALSE if no.
Determine if it is a file
In Python, you can use the os.path.isfile () function to determine whether a 1 path is a file. The function prototype is shown below.
os.path.isfile(path)
Its parameter path is the path to be judged. Returns TRUE if yes, FALSE if no.