How to create nested directories safely in Python

What is the most elegant way to check whether there is a file directory, and if not, how to use Python to create the directory? This is what I've used in the method:

 

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

f = file(filename)
Somehow, I missed os.path.exists. Now we recommend the use of this method:

 

 

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

 



Category Quantity: python basis>  Modules, Library


Author: Dream Sao years

Original link:  http://www.pythonheidong.com/blog/article/33/

Source: python black hole net  www.pythonheidong.com

Guess you like

Origin www.cnblogs.com/fuchen9527/p/10962180.html