我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。

也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?


当前回答

你可以使用Megath。

# Create a directory and any missing ancestor directories. 
# If the directory already exists, do nothing.

from distutils.dir_util import mkpath
mkpath("test")    

请注意,它也将创建祖先目录。

它适用于Python 2和3。

其他回答

如果你考虑下列事项:

os.path.isdir('/tmp/dirname')

这意味着一个目录(路径)存在,而且是一个目录,所以对我来说,这就是我所需要的,所以我可以确保它是文件夹(不是文件)并且存在。

在Python中做到这一点的最佳方法

#Devil
import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
    os.makedirs(directory)

最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:

from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)

我下载了下面的文章,但这不是完全愚蠢的。

import os

dirname = 'create/me'

try:
    os.makedirs(dirname)
except OSError:
    if os.path.exists(dirname):
        # We are nearly safe
        pass
    else:
        # There was an error on creation, so make sure we know about it
        raise

如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。

从 Python 3.5 开始, pathlib.Path.mkdir 有一个 exist_ok 旗帜:

from pathlib import Path
path = Path('/my/directory/filename.txt')
path.parent.mkdir(parents=True, exist_ok=True) 
# path.parent ~ os.path.dirname(path)

此可重复创建目录,如果目录已经存在,则不会产生例外。

(就像 os.makedirs 得到 exist_ok 旗帜从 python 3.2 e.g os.makedirs(路径, exist_ok=True))


注意:当我发表这个答案时,没有其他提到的答案存在_OK...