This article mainly introduces the Create folder User-defined function mkdir () written in Python. folder operations are frequently required in programming, and mkdir functions are even more classic, you can refer to Python to easily operate files. you only need to include the OS module and use related functions to create directories.
Three functions are involved:
1. OS. path. exists (path) determines whether a directory exists.
2. OS. makedirs (path) multi-layer directory creation
3. create a directory for OS. mkdir (path)
Directly run the code:
The code is as follows:
Def mkdir (path ):
# Introduction module
Import OS
# Remove leading space
Path = path. strip ()
# Remove tail \ symbols
Path = path. rstrip ("\\")
# Determining whether a path exists
# True
# False
IsExists = OS. path. exists (path)
# Judgment result
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 a directory exists, do not create it, and prompt that the directory already exists.
Print path + 'directory already exists'
Return False
# Define the directory to be created
Mkpath = "d :\\ qttc \ web \\"
# Call a function
Mkdir (mkpath)
The above is a function I have written. you only need to input the full path of the directory you want to create.
Description
In the DEMO function above, I didn't use the OS. mkdir (path) function, but instead used the multi-layer directory creation function OS. makedirs (path ). The biggest difference between these two functions is that when the parent directory does not exist, OS. mkdir (path) will not be created, and OS. makedirs (path) will create the parent directory.
For example, in the example, the web Directory I want to create is located in the qttc directory of disk D, but there is no qttc parent directory under disk D. If OS is used. the mkdir (path) function will prompt that the target path does not exist, but the OS is used. makedirs (path) will automatically help me create the parent directory qttc. please create the subdirectory web under the qttc directory.