mkdir -p functionality in python
Say I want to make a file:
filename = "/foo/bar/baz.txt" with open(filename, "w") as f: f.write("FOOBAR")
This gives an
/foo/bar does not exist.
What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call
os.mkdir on every single one (i.e., /foo, then /foo/bar)?
os.makedirs function does this. Try the following:
import os import errno filename = "/foo/bar/baz.txt" if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise with open(filename, "w") as f: f.write("FOOBAR")
The reason to add the
try-except block is to handle the case when the directory was created between the
os.path.exists and the
os.makedirs calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os filename = "/foo/bar/baz.txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f: f.write("FOOBAR")
Computer languages have so far been of the ‘interpreted’ or the ‘compiled’ type. Compiled languages (like ‘C’) have been more common. You prepare a program, save it (the debugged version),...
Python Crash Course is the world's best-selling guide to the Python programming language. This quick and in-depth introduction to Python programming will get you started writing programs, solving prob...
It would be easy for me to develop native apps using Java, C++ or Objective-C and I am also able to learn Kotlin, Dart or Swift, but things are much easier when you just use Python. I have done a Djan...
Cloud computing provides the capability to use computing and storage resources on a metered basis and reduce the investments in an organization’s computing infrastructure. The spawning and deletion ...