p functionality in Python

This question already has an answer here:

  • How can I create a directory if it does not exist? 26 answers

  • mkdir -p functionality as follows:

    import errno    
    import os
    
    
    def mkdir_p(path):
        try:
            os.makedirs(path)
        except OSError as exc:  # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise
    

    Update

    For Python ≥ 3.2, os.makedirs has an optional third argument exist_ok that, when true, enables the mkdir -p functionality —unless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously.

    Update 2

    For Python ≥ 3.5, there is also pathlib.Path.mkdir :

    import pathlib
    
    pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
    

    The exist_ok parameter was added in Python 3.5.


    In Python >=3.2, that's

    os.makedirs(path, exist_ok=True)
    

    In earlier versions, use @tzot's answer.


    This is easier than trapping the exception:

    import os
    if not os.path.exists(...):
        os.makedirs(...)
    

    Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaway script running in a controlled environment, you're better off going with the accepted answer that requires only one system call.

    UPDATE 2012-07-27

    I'm tempted to delete this answer, but I think there's value in the comment thread below. As such, I'm converting it to a wiki.

    链接地址: http://www.djcxy.com/p/9264.html

    上一篇: 如何创建新文件夹?

    下一篇: Python中的p函数