file creation
folder creation
directory management
file system
programming tips

How do I create a file AND any folders, if the folders don't exist?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a file safely often means solving two problems in order: make sure the parent directories exist, then create or write the file. Most languages have built-in helpers for both steps, and the usual best practice is to create directories idempotently before opening the file.

The Core Pattern

The general pattern is always the same:

  1. compute the target path
  2. create parent directories if needed
  3. create or write the file

If you try step three first and the folders do not exist, the write fails.

Python Example With pathlib

Modern Python code is especially clean with pathlib.

python
1from pathlib import Path
2
3path = Path("output/reports/summary.txt")
4path.parent.mkdir(parents=True, exist_ok=True)
5path.write_text("hello\n", encoding="utf-8")

This creates output and reports if they do not already exist, then writes the file.

parents=True means intermediate directories may be created. exist_ok=True means the call is safe even if the folder is already there.

Python Example With open()

If you prefer the traditional file API, the pattern is the same.

python
1from pathlib import Path
2
3path = Path("logs/app/run.log")
4path.parent.mkdir(parents=True, exist_ok=True)
5
6with path.open("w", encoding="utf-8") as f:
7    f.write("started\n")

The key is still creating the parent directory first.

Node.js Example

Node has the same concept using fs.mkdirSync or fs.promises.mkdir with recursion.

javascript
1const fs = require("fs");
2const path = require("path");
3
4const filePath = path.join("output", "reports", "summary.txt");
5fs.mkdirSync(path.dirname(filePath), { recursive: true });
6fs.writeFileSync(filePath, "hello\n", "utf8");

recursive: true is the part that creates the full folder chain when needed.

C# Example

C# also separates directory creation from file writing.

csharp
1using System;
2using System.IO;
3
4class Program
5{
6    static void Main()
7    {
8        string filePath = Path.Combine("output", "reports", "summary.txt");
9        Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
10        File.WriteAllText(filePath, "hello\n");
11    }
12}

Directory.CreateDirectory is convenient because it succeeds even if the directory already exists.

Why This Pattern Is Safe

Creating the directory first is usually idempotent. If the path already exists, the directory call typically does nothing harmful. That makes the code simpler than manually checking whether each parent folder exists before deciding to create it.

In other words, prefer:

  • create directory with an idempotent call
  • then write the file

instead of:

  • check if directory exists
  • branch manually
  • then write the file

Appending Versus Creating

If you want to append instead of overwrite, the pattern still starts with directory creation.

python
1from pathlib import Path
2
3path = Path("logs/app/run.log")
4path.parent.mkdir(parents=True, exist_ok=True)
5
6with path.open("a", encoding="utf-8") as f:
7    f.write("next line\n")

The file open mode changes, but the directory preparation stays the same.

Common Pitfalls

The biggest pitfall is trying to write the file before creating the parent directories. That leads to file-not-found errors even though the filename itself is valid.

Another issue is creating the full file path as a directory by mistake. You usually want the parent directory, not the file path, in the directory creation call.

Developers also overcomplicate the code with separate existence checks. Most standard directory creation APIs are already safe to call when the folder exists.

Finally, do not ignore permissions. If the process cannot create folders or files in the target location, the logic is correct but the operation still fails.

Summary

  • Create parent directories first, then create or write the file.
  • Prefer idempotent directory-creation APIs such as mkdir(..., exist_ok=True) or CreateDirectory(...).
  • Use the parent path, not the file path itself, when creating directories.
  • The same pattern works across Python, Node.js, C#, and many other languages.
  • Existence checks are often unnecessary because modern directory helpers already handle the "already exists" case.

Course illustration
Course illustration

All Rights Reserved.