LoginSignup
1
0

More than 5 years have passed since last update.

Python2で再帰的にディレクトリを作成する方法

Posted at

例外のerrnoがEEXISTであれば握りつぶせば良いです。

import sys,os,errno

def makedirs(name, mode=0o777, exist_ok=False):
    if not exist_ok:
        os.makedirs(name,mode=mode)
    elif sys.version_info[0]>=3:
        os.makedirs(name,mode=mode,exist_ok=exist_ok)
    else:
        try:
            os.makedirs(name,mode=mode)
        except OSError as e:
            if e.errno!=errno.EEXIST:
                raise e

makedirs(dir,exist_ok=True)

上に書いたことは全て茶番です。すみません。

https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist に書いてありますが、pathlib2をインストールして、

import pathlib2
pathlib2.Path(dir).mkdir(parents=True,exist_ok=True)

とするのが正解です。

なお、記事名にPython2とあるのは、上のコードを見ればわかりますが、Python3では例外を握りつぶすコードパスをそもそも通らないからです。普通に書けるってこと。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0