文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.99 [2004-09-26 01:34:30]

1. 描述

Creating Directories Including Necessary Parent Directories

创建新目录,如果有父目录,也一同创建

Credit: Trent Mick, Alex Martelli

1.1. 问题 Problem

You want a way to make a directory that is more convenient than Python's standard os.mkdir.

需要一个比直接使用os.mkdir函数创建目录更方便的方法,

1.2. 解决 Solution

A good make-directory function should, first of all, make the necessary parent directories, which os.makedirs does quite nicely. We also want our function to complete silently if the directory already exists but to fail if the needed directory exists as a plain file. To get that behavior, we need to write some code:

创建目录的方法必须创建父目录,同os.makedirs一样。 如果目录已经存在,方法应该悄悄返回,但是如果欲创建的目录已经作为一个普通文件存在,则抛出异常。代码如下

#!ptyhon
import os, errno
def mkdirs(newdir, mode=0777):
    try: os.makedirs(newdir, mode)
    except OSError, err:
        # Reraise the error unless it's about an already existing directory 
        if err.errno != errno.EEXIST or not os.path.isdir(newdir):  
            raise

1.3. 讨论 Discussion

Python's standard os.mkdir works much like the underlying mkdir system call (i.e., in a pretty spare and rigorous way). For example, it raises an exception when the directory you're trying to make already exists. You almost always have to handle that exception, because it's not generally an error if the directory already exists as a directory, while it is indeed an error if a file of that name is in the way. Further, all the parent directories of the one you're trying to make must already exist, as os.mkdir itself only makes the leaf directory out of the whole path.

标准os.mkdir函数同底层系统调用mkdir工作方式(很简单,很精确)基本一样。比如,欲创建的目录已经存在,会抛出异常。大多数情况下不得不处理这个异常:如果是目录已经存在,基本上不算是一个错误,但如果欲创建的目录的名称已经作为一个文件存在,就确实是个错误了. 还有,由于os.mkdir仅仅创建路径参数末尾的子路径,必须保证欲创建目录的父目录已经存在。

There used to be a time when mkdir, as used in Unix shell scripts, worked the same way, but we're spoiled now.

过去Unix shell脚本中的mkdir,工作方式也是同上面一样,但是现在好了.(#译注:??)

For example, the --parents switch in the GNU version of mkdir implicitly creates all intermediate directories, and gives no error if the target directory already exists as a directory.

比如, GNU版本的mkdir函数,--parent开关参数隐式创建各级父目录,如果父目录已经存在,并不返回错误常数。

  • Well, why not have the same convenience in Python? This recipe shows it takes very little to achieve this梩he little function mkdirs can easily become part of your standard bag of tricks. Of course, Python's standard os.makedirs is doing most of the job.

Python为啥没有这个方便的方法呢? 本节代码仅仅使用少许努力就获得了这种便利。上面的轻巧函数mkdirs很容易装进你的锦囊袋。当然,大部分工作是由os.makedirs函数作的。

However, mkdirs adds the important convenience of not propagating an exception when the requested directory already exists and is indeed a directory. However, if the requested directory exists as a file or if the operating system diagnoses any other kind of trouble, function mkdirs does explicitly re-raise the exception, to ensure it propagates further.

如果欲创建目录已经作为目录存在,os.makdirs会抛出异常,这很不方便,上面脚本makedirs有效处理了这个问题。如果欲创建目录是作为一个文件存或者有其他问题,makedirs会重新抛出这个异常,保证传递异常。

1.4. 参考 See Also

文档os模块部分

食谱1.5 关于Easier to Ask Forgiveness than Permission" 的解释 http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d1_2d5