# Keep every run: name each CSV file by its start time | Spider

Name each crawl's CSV file after the UTC time the run started, so a second run writes a new file beside the first. Two dated runs, two files, 20 rows each.

Canonical: https://spider.cloud/learn/course/keep-every-run/

To keep every run of a scraper, build each output file's name from the moment the run started, written in UTC with the year first and the second last, such as `quotes-2026-11-20T223358Z.csv`. Runs that start in different seconds then write to different names, and sorting the folder by name lists the runs in the order they happened.

After this lesson you have two CSV files in a `runs/` folder, one per crawl, and a script called `keep_runs.py` that adds another file each time you start it a second or more after the last start. Lesson 9 wrote to whatever name you typed, so the same name meant the same file.

## The file a second run empties

[Lesson 9](/learn/course/save-to-csv/) ended with `crawl_csv.py`, which crawls up to 20 pages and writes one row per page to whatever file name you pass it. Pass `quotes.csv` twice and the second run opens that name with `"w"`, which empties it first. Yesterday's rows are gone before today's are written.

## A name that sorts by time

The file name has one job here, and it is to differ for every run. A counter would do that. A time also tells you when the run happened, before you open the file.

The order of the parts matters. RFC 3339, the IETF's format for timestamps on the internet, says "If date and time components are ordered from least precise to most precise, then a useful property is achieved." The same paragraph names the property: when every time uses the same zone and the same suffix, "the date and time strings may be sorted as strings … and a time-ordered sequence will result." Year, month, day, hour, minute, second, in that order, all in UTC, and an ordinary `ls` puts your runs on a timeline.

UTC also gives the letter at the end. The RFC defines `Z` as "A suffix which, when applied to a time, denotes a UTC offset of 00:00". The script asks Python for the time with `timezone.utc`, so the `Z` in the name tells the truth.

The full RFC 3339 form puts colons between hour, minute and second. A file name cannot keep them if anyone will open the folder on Windows. Microsoft's page on naming files says you may "Use any character in the current code page for a name … except for the following", and the colon is on that list. The script drops the colons and writes `223358` for 22:33:58. Every name still has the same length and the same layout, so the sort still holds.

## What changed in keep_runs.py

`keep_runs.py` is `crawl_csv.py` with the file name taken out of your hands. It now takes one argument, the URL. It imports `datetime` and `timezone`, and it reads the clock once, into `started`, just before it builds the request. After the rows are ready it makes the `runs` folder with `os.makedirs("runs", exist_ok=True)` and builds the name from `started` with `strftime`. The step that read the file back and printed its first lines is gone, so the script prints one line per run.

The `exist_ok=True` part is what lets the second run reach the write. Python's documentation for `os.makedirs` says "If exist_ok is False (the default), a FileExistsError is raised if the target directory already exists." The first run creates `runs/`, and without that flag the second run would stop at that line.

The key still comes from the `SPIDER_API_KEY` environment variable. This is the script exactly as it ran twice on 2026-11-20, under Python 3.14.7:

```python
"""Crawl a site through the Spider API, at most 20 pages, and save each run to its own CSV file.

    python3 keep_runs.py URL

The file name holds the run's start time in UTC, so a second run never overwrites the first.
Exit 0: every page answered 200 and the file is written.
Exit 1: the key is missing, nothing came back, or a page answered something else.
"""
import csv
import json
import os
import sys
import urllib.request
from datetime import datetime, timezone

API = "https://api.spider.cloud/crawl"


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: python3 keep_runs.py URL")
        return 1
    url = sys.argv[1]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    started = datetime.now(timezone.utc)
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
    req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        pages = json.load(resp)
    if isinstance(pages, dict):
        pages = [pages]
    if not pages:
        print("nothing came back")
        return 1

    rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                   for p in pages))
    os.makedirs("runs", exist_ok=True)
    out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
    with open(out, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["url", "status", "bytes"])
        writer.writerows(rows)

    print(f"saved: {len(rows)} rows to {out}")
    return 0 if all(status == 200 for _, status, _ in rows) else 1


if __name__ == "__main__":
    sys.exit(main())
```

The recorded runs sent no `user_agent` and no `delay`. Yours should send both. Change the `params` line to this, with your own bot name and contact address:

```python
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
              "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}
```

The API reference describes `delay` as milliseconds to wait between requests, so 1000 is one second. Why the pause is worth it is the subject of [lesson 4 on pacing](/learn/course/pace-your-requests/).

## When two runs share a second

The name stops at whole seconds. Two runs started inside the same second get the same name, and the script as recorded opens it with `"w"`, which Python's documentation for `open()` describes as "open for writing, truncating the file first". The second run would empty the first run's file and write its own rows. A job you start by hand, or on a schedule minutes apart, will not hit that, but the script does nothing to stop it.

In your copy, change the mode on the `open` line from `"w"` to `"x"`. The same table in Python's documentation gives `"x"` as "open for exclusive creation, failing if the file already exists". With that one letter, a run that lands on a name already in `runs/` stops with `FileExistsError` and the earlier file keeps its rows:

```python
    with open(out, "x", newline="", encoding="utf-8") as f:
```

The run that stopped wrote nothing, so start it again a second later and it gets a name of its own.

## Run it twice

Start the script, wait for it to finish, and start it again with the same address:

```bash
python3 keep_runs.py https://quotes.toscrape.com/
python3 keep_runs.py https://quotes.toscrape.com/
```

These are the two runs from 2026-11-20. The first took 6.5 seconds, exited 0 and printed this:

```text
saved: 20 rows to runs/quotes-2026-11-20T223358Z.csv
```

The second took 5.4 seconds, also exited 0, and printed this:

```text
saved: 20 rows to runs/quotes-2026-11-20T223410Z.csv
```

## The files the two runs wrote

Each save line names the one file its run wrote. Here they are side by side, with the data rows each run reported. Anything else already in your `runs/` folder is not on this list:

| File the run wrote              | Run started (UTC)   | Data rows |
| ------------------------------- | ------------------- | --------- |
| `quotes-2026-11-20T223358Z.csv` | 2026-11-20 22:33:58 | 20        |
| `quotes-2026-11-20T223410Z.csv` | 2026-11-20 22:34:10 | 20        |

## Read the two names

The names differ in their last six digits, 223358 and 223410, so the second run started 12 seconds after the first. The recorded script opened its own new name with `"w"`, and the first file's name appears nowhere in that run. That is the whole fix. Lesson 9's script would have handed both runs the same name.

Both runs exited 0. The script returns 0 only when every row has status 200, so all 40 rows across the two files are pages that answered 200. Each file also has a header row, which the count of 20 leaves out.

The names already sort in the order the runs happened, and `ls runs/` will list them that way. Sites change between crawls. With the earlier file still on disk you can set two crawls of the same [web scraping](/web-scraping/) job next to each other, row by row, without guessing which one came first.

## Try it yourself

Every file you keep is one more full crawl of a site, so run a job only as often as your question needs a new file. On the practice site, change `"limit": 20` to `"limit": 5` in your copy, keep the `user_agent`, `delay` and `"x"` changes you made, and run the script twice more. Then look at the folder and count the lines in each file:

```bash
python3 keep_runs.py https://quotes.toscrape.com/
echo $?
python3 keep_runs.py https://quotes.toscrape.com/
echo $?
ls runs/
wc -l runs/*.csv
```

You are done when both `echo $?` lines print 0, `ls runs/` shows two new names after the older ones with later times in them, and `wc -l` gives each new file one more line than the row count its run printed, because the header takes a line.

## Do this, avoid this

### Do this

- Read the clock once per run and build the file name from that one value.
- Write the time in UTC, year first and second last, and end it with Z.
- Keep file names to digits, letters, hyphens and the T, with no colons.
- Open each run file in x mode, so a name clash stops the run and leaves the older file whole.
- Decide how long you keep old run files, and delete them when that time is up if the rows hold personal data.

### Avoid this

- Reusing one fixed file name for a job you run more than once.
- Naming files by local time, which carries no zone in the name.
- Opening run files in w mode, which empties a file that already has the name.
- Keeping every run file forever only because the names never clash.

## Next

The `runs/` folder now says what each crawl found and when it started. It does not say how long the crawl took, which address it began from, or how it ended. The next lesson asks how to write that down in a run log that sits beside the CSV files.

## Sources

1. [RFC 3339, Date and Time on the Internet: Timestamps, IETF, July 2002](https://www.rfc-editor.org/rfc/rfc3339.html) Read November 21, 2026
2. [Python documentation, os: Miscellaneous operating system interfaces, os.makedirs](https://docs.python.org/3/library/os.html) Read November 21, 2026
3. [Microsoft Learn, Naming Files, Paths, and Namespaces](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file) Read November 21, 2026
4. [Python documentation, Built-in functions, open()](https://docs.python.org/3/library/functions.html) Read November 21, 2026
