Skip to content
Advertisement

Write file to a directory that doesn’t exist

How do I using with open() as f: ... to write the file in a directory that doesn’t exist.

For example:

JavaScript

Let’s say the /Users/bill/output/ directory doesn’t exist. If the directory doesn’t exist just create the directory and write the file there.

Advertisement

Answer

You need to first create the directory.

The mkdir -p implementation from this answer will do just what you want. mkdir -p will create any parent directories as required, and silently do nothing if it already exists.

Here I’ve implemented a safe_open_w() method which calls mkdir_p on the directory part of the path, before opening the file for writing:

JavaScript

Updated for Python 3:

JavaScript
Advertisement