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

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


当前回答

我使用os.path.exists(),这里是一个Python 3脚本可以用来检查是否有一个目录,创建一个如果它不存在,并删除它如果它存在(如果需要)。

它鼓励用户输入目录,并且可以轻松修改。

其他回答

为什么不使用子过程模块,如果运行支持命令 mkdir 的机器与 -p 选项? 在 Python 2.7 和 Python 3.6 上工作

from subprocess import call
call(['mkdir', '-p', 'path1/path2/path3'])

应该在大多数系统上进行技巧。

在移动性不在乎的情况下(例如,使用 docker)的解决方案是干净的2行,你也不需要添加逻辑来检查是否有目录。

如果您需要错误处理:

from subprocess import check_call
try:
    check_call(['mkdir', '-p', 'path1/path2/path3'])
except:
    handle...

我看到了Heikki Toivonen和A-B-B的答案,并思考了这种变异。

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST or not os.path.isdir(path):
            raise

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

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

你可以使用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')

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