SoFunction
Updated on 2024-10-29

Python writes mkdir, a custom function for creating folders.

Python on the file operation is still convenient, just need to include os module in, using the relevant functions to achieve the creation of directories.

There are three main functions involved: the

1、(path) Determine whether a directory exists.
2、(path) Multi-level creation of directories
3、(path) Create directory

Straight to the code.

Copy Code The code is as follows.

def mkdir(path):
# Introducing Modules
    import os
 
# Remove first space
    path=()
# Remove trailing \ symbol
    path=("\\")
 
# Determine if a path exists
# Existing True
# Not available False
    isExists=(path)
 
# Judgment results
    if not isExists:
# Create directory if it doesn't exist
print path+' Created successfully'
# Create directory manipulation functions
        (path)
        return True
    else:
# If the directory exists it is not created and prompts that the directory already exists
print path+' Directory already exists'
        return False
 
# Define the directory to be created
mkpath="d:\\qttc\\web\\"
# Calling functions
mkdir(mkpath)

Above is a function I wrote, just pass in the full path to the directory you want to create.

clarification

In the function in the DEMO above, I didn't use the (path) function, but instead used the multi-layer create directory function (path). The big difference between these two functions is that (path) doesn't create the parent directory when it doesn't exist, and (path) creates the parent directory.

For example: in the example, the directory web I want to create is located in the qttc directory on the D drive, however, I don't have a qttc parent directory under the D drive, if I use the (path) function it will prompt me that the target path doesn't exist, but using (path) it will automatically create the parent directory qttc for me, so please create a subdirectory web under the qttc directory.