牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Python でファイル作成する時に指定したディレクトリが無ければ作るメモ

(python2.7.11)

ディレクトリが無いとこで open して write するとエラーになるので mkdir する

# coding=utf-8
import os


def write(filename, text):
    file_path = os.path.dirname(filename)
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    with open(filename, 'w') as f:
        f.write(text)


write('/tmp/foo/bar.txt', 'hello!')