Python Write Create folder Custom function mkdir ()

Source: Internet
Author: User
Python's operation of the file is also convenient, only need to include the OS module in, using the relevant functions to achieve the creation of the directory.

There are three main functions involved:

1. Os.path.exists (path) to determine if a directory exists
2. Os.makedirs (path) multi-layer Create directory
3. Os.mkdir (path) Create directory

Directly on the code:

Copy the Code code as follows:


def mkdir (path):
# Introduction Module
Import OS

# Remove First space
Path=path.strip ()
# remove tail \ Symbol
Path=path.rstrip ("\ \")

# Determine if the path exists
# exists True
# does not exist False
Isexists=os.path.exists (PATH)

# Judging Results
If not isexists:
# Create a directory if it does not exist
Print path+ ' created successfully '
# Create a directory operation function
Os.makedirs (PATH)
Return True
Else
# If the directory exists, do not create and prompt the directory already exists
Print path+ ' directory already exists '
Return False

# define the directory to be created
Mkpath= "D:\\qttc\\web\\"
# Call function
mkdir (Mkpath)

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

Description

In the above demo function, I did not use the Os.mkdir (path) function, but instead used multiple layers to create the directory function os.makedirs (path). The biggest difference between the two functions is that os.mkdir (path) is not created when the parent directory does not exist, and Os.makedirs creates the parent directory.

For example: In the example I want to create the directory Web is located in the D-disk QTTC directory, but I do not have QTTC under the D disk parent directory, if you use the Os.mkdir (path) function will prompt me the target path does not exist, but use Os.makedirs (path) will automatically help me create the parent directory QTTC, create the subdirectory Web under the QTTC directory.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.