Create folder custom functions written by Python mkdir () _python

Source: Internet
Author: User
Tags create directory mkdir parent directory

Python is handy for file manipulation, just include OS modules in, and use related functions to create the directory.

Mainly involves three functions:

1, os.path.exists (path) to determine whether a directory exists
2. Os.makedirs (path) multi-layer Creation directory
3, Os.mkdir (path) to create a directory

Directly on the code:

Copy Code code as follows:

def mkdir (path):
# Introduce modules
Import OS

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

# to determine if a path exists
# exists True
# there is no False
Isexists=os.path.exists (PATH)

# Judging Results
If not isexists:
# Create a directory if it doesn't exist
Print path+ ' Create success '
# Create directory Action functions
Os.makedirs (PATH)
Return True
Else
# If the directory exists then do not create and hint that the directory already exists
Print path+ ' directory already exists '
Return False

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

The above is a function that I wrote, only need to pass in you want to create the full path of the directory.

Description

In the above demo's function, I did not use the Os.mkdir (path) function, but used the Multi-layer creation 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 (path) creates the parent directory.

For example, the directory Web I want to create is located in the QTTC directory in D disk, but I do not have the QTTC parent directory under D disk, if using the Os.mkdir (path) function prompts me that the destination path does not exist, but uses os.makedirs (path) will automatically help me create the parent directory QTTC, please create the subdirectory Web in the QTTC directory.

Related Article

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.