How can I safely create a nested directory in Pyth

2018-12-31 05:36发布

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

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)

Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

Is there a flag for "open", that makes this happen automatically?

25条回答
闭嘴吧你
2楼-- · 2018-12-31 06:22

Check os.makedirs: (It makes sure the complete path exists.)
To handle the fact the directory might exist, catch OSError. (If exist_ok is False (the default), an OSError is raised if the target directory already exists.)

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass
查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 06:22

Starting from Python 3.5, pathlib.Path.mkdir has an exist_ok flag:

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

This recursively creates the directory and does not raise an exception if the directory already exists.

(just as os.makedirs got an exist_ok flag starting from python 3.2 e.g os.makedirs(path, exist_ok=True))

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 06:22

Use this command check and create dir

 if not os.path.isdir(test_img_dir):
     os.mkdir(str("./"+test_img_dir))
查看更多
孤独寂梦人
5楼-- · 2018-12-31 06:23

In Python3, os.makedirs supports setting exist_ok. The default setting is False, which means an OSError will be raised if the target directory already exists. By setting exist_ok to True, OSError (directory exists) will be ignored and the directory will not be created.

os.makedirs(path,exist_ok=True)

In Python2, os.makedirs doesn't support setting exist_ok. You can use the approach in heikki-toivonen's answer:

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
查看更多
爱死公子算了
6楼-- · 2018-12-31 06:24

Try the os.path.exists function

if not os.path.exists(dir):
    os.mkdir(dir)
查看更多
无色无味的生活
7楼-- · 2018-12-31 06:24

Why not use subprocess module if running on a machine that supports shell languages? Works on python 2.7 and python 3.6

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

Should do the trick on most systems.

查看更多
登录 后发表回答