DEV Community

Prarit Sidana
Prarit Sidana

Posted on Originally published at praritsidana.com Fully Autonomous

Write a file inventory to CSV with Python

A file inventory workflow with a separate CSV verification step

AI-assisted article. The file-inventory example was checked with temporary fixtures, including empty folders and filenames that require CSV quoting.

Python automation works well when a repeatable task has a clear input and a result you can check. A file inventory is a practical first exercise: take one folder and produce a table of file names and sizes. The report can help review a download folder or prepare a list of documents before a larger workflow.

Start with a small folder

Create a folder named sample-files and add two small text files. The example below lists files directly inside that folder. It skips subfolders and symbolic links, reads file metadata, and creates a new CSV report. It does not rename, move or edit the source files.

Python's standard library supplies pathlib for working with paths and csv for writing the table. Save this example as inventory.py:

import csv
from pathlib import Path


def spreadsheet_text(value):
    if value.startswith(("=", "+", "-", "@", "\t", "\r", "\n")):
        return "'" + value
    return value


def build_inventory(source, output):
    if not source.is_dir():
        raise ValueError("Source must be an existing folder")
    rows = []
    for item in sorted(source.iterdir(), key=lambda p: p.name.casefold()):
        if item.is_symlink() or not item.is_file():
            continue
        rows.append({
            "filename": spreadsheet_text(item.name),
            "bytes": item.stat().st_size,
        })
    with output.open("x", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=["filename", "bytes"])
        writer.writeheader()
        writer.writerows(rows)
    return len(rows)


if __name__ == "__main__":
    count = build_inventory(Path("sample-files"), Path("inventory.csv"))
    print(f"Recorded {count} files")
Enter fullscreen mode Exit fullscreen mode

Run the script from the directory containing sample-files:

python inventory.py
Enter fullscreen mode Exit fullscreen mode

The output is inventory.csv in the current directory. Opening it with mode x prevents an existing report from being overwritten. Choose a new output name for another run. The CSV writer handles commas and quotes inside names; UTF-8 preserves non-English characters. The small spreadsheet_text function prefixes names beginning with formula characters so they can be treated as text when reviewed in a spreadsheet.

Verify the result before scheduling it

An empty source folder should produce a report containing only the filename and bytes header. A source with two files and one subfolder should produce two data rows. Compare the reported sizes with the source files, and check that their names and contents have not changed. Try a filename containing a comma and another containing non-English characters.

Missing folders, unavailable output directories and permission problems need attention. The example raises an exception rather than reporting a successful run when it cannot finish. A production command should turn that failure into a clear log entry or alert.

This implementation collects rows in memory and is intended for small folders. It is not a consistent snapshot if another program changes files while the inventory runs. Before adapting it for a busy shared drive, decide whether to skip changed files, retry them or use a storage snapshot.

Grow the workflow gradually

Once the manual command is predictable, schedule it with the operating system's task scheduler. Use a unique output name for each run and check the result and exit status. Scheduling alone does not make a script reliable.

Separate the input scan from the output writer so each part can be checked with a small fixture. Keep the first scheduled run limited to a folder whose contents you can compare manually.

References: Python's official pathlib documentation and CSV documentation. The example was checked with temporary test files, including empty folders and filenames requiring CSV quoting.

Originally published on Prarit Sidana's portfolio.

Top comments (0)