Write a String to a File with mkdir in Python

October 2020

This is how I output strings to files in Python while making and necessary parent directories.

import os
import os.path

def write_file_with_mkdir(content, path):
    dir = os.path.dirname(path)
    if dir != "":
        os.makedirs(dir, exist_ok=True)
    with open(path, "w") as _out:
        _out.write(content)


if __name__ == "__main__":
    content = "the quick brown fox"
    path = "subdir/python-output.txt"
    write_file_with_mkdir(
        content, path
    )
end of line