Python writes the create folder custom function mkdir of

  • 2020-04-02 14:00:39
  • OfStack

Python's operation of the file is relatively convenient, just need to include the OS module in, using related functions to achieve the creation of directory.

There are mainly three functions involved:

1. Os.path. Exists (path) determines whether a directory exists
2. Os.makedirs (path) multi-layer directory creation
Os.mkdir (path) creates directories

Direct code:


def mkdir(path):
    # The introduction of the module
    import os
 
    # Remove the first space
    path=path.strip()
    # Remove the tail symbol
    path=path.rstrip("\")
 
    # Determine if the path exists
    # There are      True
    # There is no    False
    isExists=os.path.exists(path)
 
    # Determine the results
    if not isExists:
        # If it does not exist, create a directory
        print path+' Creating a successful '
        # Create the directory action function
        os.makedirs(path)
        return True
    else:
        # If the directory exists, it is not created, and the directory is prompted to exist
        print path+' Directory already exists '
        return False
 
# Define the directory to create
mkpath="d:\qttc\web\"
# Call a function
mkdir(mkpath)

Above is a function that I have written, just pass in the full path of the directory you want to create.

instructions

In the DEMO above, instead of os.mkdir(path), I used multiple layers to create the directory function os.makedirs(path). The big difference between these two functions is that os.mkdir(path) is not created when the parent directory does not exist, and os.makedirs(path) creates the parent directory.

For example, the directory web I want to create in the example is located in the QTTC directory of disk D, but I don't have a QTTC parent directory in disk D. If I use the os.mkdir(path) function, it will remind me that the target path does not exist, but using os.makedirs(path) will automatically help me create a parent directory QTTC, please create a subdirectory web in the QTTC directory.


Related articles: