一、 OS module creation directory

The OS module is a module in Python used to access operating system functions, which includes operations such as creating, deleting, and moving files and folders. Creating a directory using the OS module does not require additional installation of third-party libraries, making it very convenient and practical.

The following is an example of using the OS module to create a directory:


 

 

 

Among them, the mkdir() function is used to create a directory, and the parameter is the directory name string. Through this function, a directory named 'my_folder' can be created. If the directory already exists, an exception will be thrown.

In addition, the os. makedirs() function can also be used to create multi-level nested directories:


 

 

 

The above code will create a directory called "my_folder1/my_folder2".

二、 Pathlib module creation directory

The pathlib module is a module used in the Python standard library to handle path operations, providing a more intuitive and practical method than the OS module. In Python 3.4 and above, pathlib has become a part of the standard library and does not require additional installation.

The method to create a directory using the pathlib module is as follows:


 

 

 

In the above code, define current_ Path is the current path, dir_ The name is the directory name that needs to be created, and the "/" symbol is used to connect two path parts to obtain the complete path. Finally, use the mkdir() function to create a directory, with the parameter directory name string. At this point, a directory named "my_folder" will be created under the current path.

三、 SHUTIL module creation directory

The SHUTIL module is a module used for advanced file operations in the Python standard library, providing functions such as copying, moving, renaming, and deleting. Among them, the makedirs() function of the SHUTIL module can create multiple nested directories.

The following is a code example of using the SHUTIL module to create a directory:


 

 

 

The above code will create a directory called "my_folder1/my_folder2". If the directory already exists, it will not have any impact.