Sub topic 4
A project layout that separates code, data, and outputs
This chapter assumes you can write basic Python, use Jupyter, run shell commands, and commit with Git. It also assumes you have used pip to install packages. The earlier chapters covered hidden state and the "restart and run all" check. This chapter covers the folder structure that makes those checks easy to run.
Why layout is a reproducibility problem
A notebook dropped into a folder full of files looks harmless. Over a few weeks the folder collects final.csv, final_v2.csv, final_v2_fixed.csv, and a few PNG files nobody can trace back to a cell. Three problems follow:
- You cannot tell which files are original inputs and which the analysis produced.
- You cannot delete generated files safely, because some of them may be the only copy of something.
- Paths such as
C:\Users\sam\Desktop\data.csvwork on one machine only.
A good layout answers one question for every file: is this something a person wrote, something a person collected, or something the code produced? Each answer gets its own place.
The three kinds of files
| Kind | Examples | Who changes it | Stored in Git? |
|---|---|---|---|
| Code | notebooks, `.py` modules, tests | You, by editing | Yes |
| Inputs | raw data, lookup tables | Nobody after download | Usually no, but record a hash |
| Outputs | cleaned data, figures, tables, executed notebooks | The code, by running | Usually no |
The key rule is a one-way flow. Code reads inputs and writes outputs. Code never writes into the inputs folder, and you never edit outputs by hand. If every output can be regenerated, you can delete the whole outputs folder and rebuild it, which is the strongest test of reproducibility.
A concrete layout
This layout works for most single-analysis projects:
my-analysis/
├── README.md
├── pyproject.toml
├── requirements.txt
├── .gitignore
├── data/
│ ├── raw/ # original files, never modified
│ ├── interim/ # temporary intermediate files
│ └── processed/ # final cleaned data used for analysis
├── notebooks/
│ ├── 01_explore.ipynb
│ └── 02_model.ipynb
├── src/
│ └── myanalysis/
│ ├── __init__.py
│ ├── paths.py
│ └── cleaning.py
├── tests/
│ └── test_cleaning.py
└── reports/
├── figures/
└── tables/Each folder has one job:
data/rawholds files exactly as you received them. If a source file has errors, fix them in code, not in the file.data/interimanddata/processedhold files the code generates. Anything here can be deleted and rebuilt.notebooksholds exploration and narrative. Number the files so the intended order is visible.src/myanalysisholds functions that you want to import and test. The chapter on refactoring covers moving logic there.reportsholds what you share: figures, tables, and rendered notebooks.README.mdstates how to set up the environment, where to get the raw data, and which command or notebook to run first.
The names are a convention, not a requirement. What matters is that the same rule holds for every file in the project.
Never hard-code paths
Absolute paths break the moment someone else clones the project. Relative paths such as ../data/raw/x.csv break when the notebook runs from a different working directory. For example, Jupyter uses the notebook's folder, while a script uses wherever you launched it.
The fix is to compute every path from the project root in one small module. Place this in src/myanalysis/paths.py:
from pathlib import Path
# paths.py lives at <root>/src/myanalysis/paths.py,
# so the project root is two folders above this file's folder.
ROOT = Path(__file__).resolve().parents[2]
RAW = ROOT / "data" / "raw"
INTERIM = ROOT / "data" / "interim"
PROCESSED = ROOT / "data" / "processed"
FIGURES = ROOT / "reports" / "figures"
TABLES = ROOT / "reports" / "tables"
def ensure_output_dirs():
"""Create output folders if they do not exist yet."""
for folder in (INTERIM, PROCESSED, FIGURES, TABLES):
folder.mkdir(parents=True, exist_ok=True)To import myanalysis from a notebook without editing sys.path, install the project in editable mode. This needs a minimal pyproject.toml at the root:
[project]
name = "myanalysis"
version = "0.1.0"
requires-python = ">=3.9"
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]Then, with your virtual environment active, run this once from the project root:
pip install -e .Now any notebook, script, or test can use the same paths, whatever its working directory:
import pandas as pd
from myanalysis.paths import RAW, PROCESSED, FIGURES, ensure_output_dirs
ensure_output_dirs()
df = pd.read_csv(RAW / "measurements.csv")
df = df.dropna()
df.to_csv(PROCESSED / "measurements_clean.csv", index=False)The notebook reads from RAW and writes to PROCESSED. It never writes to RAW.
Protecting the raw data
Convention alone does not stop an accidental overwrite. Add a mechanical guard by making the raw folder read-only after you download the files:
chmod -R a-w data/rawOn Windows, set the folders to read-only in the file properties, or keep the raw data in a location your account cannot write to. A write attempt then fails with a permission error instead of silently corrupting your input. This guard also pairs well with the checksum technique in the data provenance chapter, which catches changes the permissions miss.
What goes into Git
Git is built for small text files that change in readable steps. Code fits that description. Large data files and regenerated outputs do not. A .gitignore file makes the split explicit:
# Environment
.venv/
# Data: raw files are recorded by hash, not committed
data/raw/*
data/interim/*
data/processed/*
!data/raw/.gitkeep
!data/interim/.gitkeep
!data/processed/.gitkeep
# Generated outputs
reports/figures/*
reports/tables/*
# Notebook and Python noise
.ipynb_checkpoints/
__pycache__/
*.pycThe .gitkeep files are empty placeholders. Git does not track empty folders, so without them a fresh clone would lack the structure that your paths module expects. Create them once:
touch data/raw/.gitkeep data/interim/.gitkeep data/processed/.gitkeepSmall raw files, such as a 20 KB lookup table, can reasonably be committed. If you do commit them, remove the matching ignore line and treat the file as read-only. For large data, commit a note in the README that says where the data came from and which hash it should have. The data provenance chapter shows how to write that down.
Common mistakes
- Writing a result next to the notebook. A stray
output.csvinnotebooks/has no clear origin. Always write through the named paths. - Editing a raw file "just this once". The edit is invisible to anyone who downloads the original. Make the change in code so the repeated run applies it again.
- Treating
interimas permanent. If a later step depends on a file that only exists on your laptop, the project is not reproducible. Every file ininterimandprocessedmust be rebuildable fromrawplus code. - Copying
srccode into notebooks. Two copies drift apart. Import from the module instead. - Putting secrets in the repository. Keep API keys in environment variables or a
.envfile that is listed in.gitignore.
A quick check of your layout
Run this from the project root to verify the one-way flow. It deletes only generated files, then reruns the notebooks:
rm -rf data/interim/* data/processed/* reports/figures/* reports/tables/*
jupyter nbconvert --to notebook --execute notebooks/01_explore.ipynb --output-dir /tmp/checkIf the run succeeds and the folders fill again, your outputs are truly derived. If it fails because a file is missing, you have found a hidden dependency on a hand-made file. The next chapters on virtual environments and dependency pinning build on this foundation.
Exercise
A teammate clones your project and the notebook fails with FileNotFoundError for ../data/raw/measurements.csv, although it works for you. Give two reasons this can happen with this layout approach, and one change that fixes both.
Show answer
First, the relative path depends on the working directory, which differs between Jupyter, a script, and a command-line run. Second, the raw file is not in Git, so a fresh clone does not contain it unless the README says where to download it. Fix: read the file through RAW / "measurements.csv" from a paths module computed from the project root, and document the download source and expected hash in the README so the teammate can place the file in data/raw.
Exercise
Why does the layout keep data/processed out of Git, and what must be true for that to be safe?
Show answer
Processed files are generated by code, so storing them in Git adds large, hard-to-review files and allows them to drift from the code. It is safe only if every processed file can be rebuilt from data/raw and the committed code, which you can test by deleting the folder and rerunning the analysis.