Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中安全地创建嵌套目录?_Python_Exception_Path_Directory_Operating System - Fatal编程技术网

如何在Python中安全地创建嵌套目录?

如何在Python中安全地创建嵌套目录?,python,exception,path,directory,operating-system,Python,Exception,Path,Directory,Operating System,检查文件将要写入的目录是否存在,如果不存在,使用Python创建目录,最优雅的方法是什么?以下是我尝试过的: import os file_path = "/my/directory/filename.txt" directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename) 不知何故,我错过了os.pat

检查文件将要写入的目录是否存在,如果不存在,使用Python创建目录,最优雅的方法是什么?以下是我尝试过的:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

f = file(filename)
不知何故,我错过了os.path.exists(感谢kanja、Blair和Douglas)。这就是我现在拥有的:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
是否有一个“打开”的标志,可以自动执行此操作?

尝试此功能

检查:(确保存在完整的路径。)
要处理目录可能存在的事实,请捕获
OSError
。 (如果
exist\u ok
False
(默认设置),则如果目标目录已存在,将引发
OSError
。)

关于Python≥ 3.5、使用:

对于较旧版本的Python,我看到了两个很好的答案,每个答案都有一个小缺陷,因此我将给出我的看法:

<>试一下,考虑一下创作。

import os
if not os.path.exists(directory):
    os.makedirs(directory)
如注释和其他地方所述,存在竞争条件–如果在
os.path.exists
os.makedirs
调用之间创建目录,则
os.makedirs
将因
OSError
而失败。不幸的是,捕获
OSError
并继续操作并不是万无一失的,因为它会忽略由于其他因素(如权限不足、磁盘已满等)而导致的创建目录失败

一个选项是捕获
OSError
并检查嵌入的错误代码(请参阅):

或者,可能还有第二个
os.path.exists
,但是假设另一个在第一次检查之后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄

根据应用程序的不同,并发操作的危险可能大于或小于其他因素(如文件权限)造成的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境

Python的现代版本通过公开(在3.3+中)和

…并允许(在3.2+中)


我已记下以下内容。不过,这并不是万无一失的

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

正如我所说,这并不是万无一失的,因为我们有可能无法创建目录,并且在这段时间内还有另一个进程创建它。

我个人建议您使用
os.path.isdir()
来测试,而不是
os.path.exists()

如果您有:

>>> dir = raw_input(":: ")
和愚蠢的用户输入:

:: /tmp/dirname/filename.etc

。。。如果您使用
os.path.exists()
使用try-except进行测试,并且errno模块中正确的错误代码消除了竞争条件,并且是跨平台的,那么当您将该参数传递给
os.makedirs()
时,您将得到一个名为
filename.etc
的目录:

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
换句话说,我们尝试创建目录,但如果它们已经存在,我们将忽略错误。另一方面,会报告任何其他错误。例如,如果您事先创建了dir'a'并从中删除了所有权限,您将得到一个由
errno.EACCES
引发的
OSError
(权限被拒绝,错误13)。

Python 3.5+: 如上所述,递归创建目录,如果目录已经存在,则不会引发异常。如果不需要或不希望创建父对象,请跳过
parents
参数

Python 3.2+: 使用
pathlib

import os
os.makedirs(path, exist_ok=True)
import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
如果可以,请安装名为的当前
pathlib
后端口。不要安装名为的旧的未维护的后端口。接下来,参考上面的Python3.5+部分,并使用相同的方法

如果使用Python3.4,即使它附带了
pathlib
,它也缺少有用的
exist\u ok
选项。backport旨在提供一个更新的、更高级的
mkdir
实现,其中包括这个缺少的选项

使用
os

import os
os.makedirs(path, exist_ok=True)
import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
如上所述,递归创建目录,如果目录已经存在,则不会引发异常。只有在使用Python 3.2+时,它才具有可选的
exist\u ok
参数,默认值为
False
。Python2.x到2.7版本中不存在此参数。因此,不需要像Python 2.7那样进行手动异常处理

Python 2.7+: 使用
pathlib

import os
os.makedirs(path, exist_ok=True)
import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
如果可以,请安装名为的当前
pathlib
后端口。不要安装名为的旧的未维护的后端口。接下来,参考上面的Python3.5+部分,并使用相同的方法

使用
os

import os
os.makedirs(path, exist_ok=True)
import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
虽然一个简单的解决方案可能先使用,然后使用,但上面的解决方案颠倒了两个操作的顺序。在这样做时,它可以防止与创建目录的重复尝试有关的常见争用条件,还可以消除目录中文件的歧义

请注意,捕获异常并使用
errno
用处有限,因为
OSError:[errno 17]文件存在
,即文件和目录都会引发
errno.EEXIST
。更可靠的方法是简单地检查目录是否存在

备选方案: 创建嵌套目录,如果该目录已存在,则不执行任何操作。这在Python2和Python3中都适用

import distutils.dir_util
distutils.dir_util.mkpath(path)
根据,此替代方案的一个严重限制是,对于给定路径,每个python进程只工作一次。换句话说,如果您使用它来创建目录,然后从Python内部或外部删除该目录,然后再次使用
mkpath
来重新创建同一目录,
mkpath
只会静默地使用其先前创建该目录的无效缓存信息,而不会再次创建该目录。相反,
os.makedirs
不依赖任何这样的缓存。对于某些应用程序,此限制可能没有问题


关于目录的
import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
import distutils.dir_util
distutils.dir_util.mkpath(path)
try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise
    else:
        print "\nBE CAREFUL! Directory %s already exists." % path
if not os.path.exists(path):
    os.makedirs(path)
else:
    print "\nBE CAREFUL! Directory %s already exists." % path
if not os.path.exists(d):
    os.makedirs(d)
import errno
try:
    os.makedirs(d)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise
import tempfile

d = tempfile.mkdtemp()
mkdtemp(suffix='', prefix='tmp', dir=None)
    User-callable function to create and return a unique temporary
    directory.  The return value is the pathname of the directory.

    The directory is readable, writable, and searchable only by the
    creating user.

    Caller is responsible for deleting the directory when done with it.
from pathlib import Path
import tempfile
directory = Path(tempfile.gettempdir()) / 'sodata'
directory.mkdir(exist_ok=True)
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
    logger.info("todays_file exists: " + str(todays_file))
    df = pd.read_json(str(todays_file))
filename = "/my/directory/filename.txt"
dir = os.path.dirname(filename)
import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
if not os.path.exists(directory):
    os.makedirs(directory)
f = file(filename)
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
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)
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.
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
from IPython.utils.path import ensure_dir_exists
ensure_dir_exists(dir)
import os
if 'dirName' in os.listdir('parentFolderPath')
    print('Directory Exists')
# Create a directory and any missing ancestor directories. 
# If the directory already exists, do nothing.

from distutils.dir_util import mkpath
mkpath("test")    
os.path.isdir('/tmp/dirname')
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(path,exist_ok=True)
import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
import os
if os.path.isfile(filename):
    print "file exists"
else:
    "Your code here"
└── output/         ## dir
   ├── corpus       ## file
   ├── corpus2/     ## dir
   └── subdir/      ## dir
# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist

import pathlib

""" Notes:
        1.  Include a trailing slash at the end of the directory path
            ("Method 1," below).
        2.  If a subdirectory in your intended path matches an existing file
            with same name, you will get the following error:
            "NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:

# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but no file created (os.makedirs creates dir, not files!  ;-)
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# [2] https://docs.python.org/3/library/os.html#os.makedirs

# Uncomment these to run "Method 1":

#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)

# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## works
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## works
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# Uncomment these to run "Method 2":

#import os, errno
#try:
#       os.makedirs(out_dir)
#except OSError as e:
#       if e.errno != errno.EEXIST:
#               raise
# ----------------------------------------------------------------------------
 if not os.path.isdir(test_img_dir):
     os.mkdir(test_img_dir)
import os

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

create_dir('Project directory')
from subprocess import call
call(['mkdir', '-p', 'path1/path2/path3'])
from subprocess import check_call
try:
    check_call(['mkdir', '-p', 'path1/path2/path3'])
except:
    handle...
import os,sys,inspect
import pathlib

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"

if not os.path.exists(your_folder):
   pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
import os
os.system("mkdir -p {0}".format('mydir'))