Python determines whether the directory exists and creates if it does not exist

Source: Internet
Author: User



EG1:

If Os.path.isdir (' E:\test '):
Pass
Else
Os.mkdir (' E:\test ')

# #os. mkdir () Only one directory is created and cannot be created Cascade


EG2:

If not os.path.exists (' E:\test '): # # #判断文件是否存在, returns a Boolean value
Os.makedirs (' E:\test ')

# #os. Makedirs () This, along with the middle directory, will be created, similar to the parameter mkdir-p


EG3:

Try
fp = open ("File_path")
What is the difference between catch exception:except and catch?
Os.mkdir (' File_path ') # #os. mkdir () will create only one directory, not cascade creation, but with the awareness of exception handling
fp = open ("File_path"


EG4: Measured

#!/usr/bin/env python
Import OS
File_path= '/home/wuxy/aaa111/222/333/444.txt ' # # #444. txt does not act as a file but as a directory
If Os.path.exists (' File_path '): # # directory exists, return to True
print ' Dir NOT exists '
Os.makedirs (File_path) # # #FILE_PATH不用加引号. Otherwise it will be an error
Else
print ' dir exists '

Python determines whether the directory exists and creates if it does not exist

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.