Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mkdir -p functionality in Python [duplicate]

Is there a way to get functionality similar to mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?

like image 435
Setjmp Avatar asked Mar 01 '09 18:03

Setjmp


People also ask

How do I copy multiple files from one directory to another in Python?

For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them. Calling shutil. copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.)

What is the use of mkdir () and Mkdirs () methods in Python?

Creating a directory is a common operation in Python when you're working with files. The os. mkdir() method can be used to create a single directory, and the os. makedirs() method can be used to create multi-level directories.


2 Answers

For Python ≥ 3.5, use pathlib.Path.mkdir:

import pathlib pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True) 

The exist_ok parameter was added in Python 3.5.


For Python ≥ 3.2, os.makedirs has an optional third argument exist_ok that, when True, enables the mkdir -p functionality—unless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously:

import os os.makedirs("/tmp/path/to/desired/directory", exist_ok=True) 

For even older versions of Python, you can use os.makedirs and ignore the error:

import errno     import os  def mkdir_p(path):     try:         os.makedirs(path)     except OSError as exc:  # Python ≥ 2.5         if exc.errno == errno.EEXIST and os.path.isdir(path):             pass         # possibly handle other errno cases here, otherwise finally:         else:             raise 
like image 112
tzot Avatar answered Sep 28 '22 10:09

tzot


In Python >=3.2, that's

os.makedirs(path, exist_ok=True) 

In earlier versions, use @tzot's answer.

like image 39
Fred Foo Avatar answered Sep 28 '22 08:09

Fred Foo