Skip to content

Instantly share code, notes, and snippets.

@keenhenry
Last active October 29, 2016 16:54
Show Gist options
  • Save keenhenry/3565a567dd6654b8e01beb05f456a48a to your computer and use it in GitHub Desktop.
Save keenhenry/3565a567dd6654b8e01beb05f456a48a to your computer and use it in GitHub Desktop.
The implementation of `$ mkdir -p path` in Python: http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
if __name__=='__main__':
non_existing_path = './dir1/dir2/wtf.txt'
mkdir_p(os.path.dirname(non_existing_path))
with open(non_existing_path, 'w') as f:
f.write('WTF\n')
print('DONE')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment