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

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


当前回答

为什么不使用子过程模块,如果运行支持命令 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...

其他回答

关于这种情况的具体性

您在某个路径上提供一个特定的文件,然后从文件路径中提取目录,然后确保您有目录后,您试图打开阅读的文件。

import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)

你的最终目标是打开这个文件,你最初表示,写作,但你基本上接近这个目标(基于你的代码),如此,打开文件阅读:

如果不是 os.path.exists(地址): os.makedirs(地址) f = 文件(文件名)

為什麼你會為你期望在那裡並能夠閱讀的檔案製作一個目錄?

只是试着打开文件。

with open(filepath) as my_file:
    do_stuff(my_file)

import errno
try:
    with open(filepath) as my_file:
        do_stuff(my_file)
except IOError as error:
    if error.errno == errno.ENOENT:
        print 'ignoring error because directory or file is not there'
    else:
        raise

假设我们对写作开放

在这种情况下,我们可能不会遇到任何竞赛条件,所以只是做你是,但请注意,写作,你需要打开W模式(或一个添加)。

import os
if not os.path.exists(directory):
    os.makedirs(directory)
with open(filepath, 'w') as my_file:
    do_stuff(my_file)

import os
import errno
if not os.path.exists(directory):
    try:
        os.makedirs(directory)
    except OSError as error:
        if error.errno != errno.EEXIST:
            raise
with open(filepath, 'w') as my_file:
    do_stuff(my_file)

在 Python3 中,OS.makedirs 支持设置 exist_ok. 默认设置是 False,这意味着如果目标目录已经存在,则将升级到 OSError. 通过设置 exist_ok 到 True,则将被忽略到 OSError(目录存在)并不会创建目录。

os.makedirs(path,exist_ok=True)

在 Python2 中, os.makedirs 不支持 exist_ok 设置. 在 heikki-toivonen 的答案中,您可以使用方法:

import os
import errno

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

您可以使用 os.listdir 为此:

import os
if 'dirName' in os.listdir('parentFolderPath')
    print('Directory Exists')

在 Python 3.4 中,您还可以使用全新 pathlib 模块:

from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
    if not path.parent.exists():
        path.parent.mkdir(parents=True)
except OSError:
    # handle error; you can also catch specific errors like
    # FileExistsError and so on.

在您的程序/项目的输入点上拨打 Create_dir() 函数。

import os

def create_dir(directory):
    if not os.path.exists(directory):
        print('Creating Directory '+directory)
        os.makedirs(directory)

create_dir('Project directory')