Content · Programming · Python

Python Build a Folder Report in CSV Format

Produce a basic inventory of filenames and file sizes in a CSV report. Use csv.writer() with a text file opened using newline="" and encoding="utf-8".

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This Python tutorial explains Build a Folder Report in CSV Format. Follow the example, inspect the output, and practise an input change so you understand the behavior rather than simply copying the syntax.

What This Feature Does


Produce a basic inventory of filenames and file sizes in a CSV report.

Use csv.writer() with a text file opened using newline="" and encoding="utf-8". Store relative filenames rather than paths to unrelated parts of the computer; do not assume rows will be returned in a stable order unless sorted.

When to Use It


This technique belongs to safe file automation. It is useful when the input, operation and expected outcome are known. Start with a small controlled example before integrating it into a larger workflow.

Step-by-Step Python Example


Read the code once before running it. Notice which values are inputs, which function or method performs the work, and whether the result is returned or stored by changing an existing object.

import csv
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory_name:
    root_path = Path(directory_name)
    (root_path / "alpha.txt").write_text("Alpha", encoding="utf-8")
    (root_path / "beta.txt").write_text("Beta", encoding="utf-8")
    report_path = root_path / "report.csv"
    with report_path.open("w", newline="", encoding="utf-8") as report_stream:
        report_writer = csv.writer(report_stream)
        report_writer.writerow(["filename", "size_bytes"])
        for document_path in sorted(root_path.glob("*.txt")):
            report_writer.writerow([document_path.name, document_path.stat().st_size])
    print(report_path.read_text(encoding="utf-8").splitlines()[0])

Understanding the Code


  • First, the imports make csv, pathlib, tempfile available. They provide the filesystem, data or standard-library functions used later.
  • Find the call TemporaryDirectory(). Its parameters determine the specific operation demonstrated in the title.
  • Its purpose is to produce a basic inventory of filenames and file sizes in a csv report. Compare this description against the result printed by the program.
  • The sample uses TemporaryDirectory() so any practice files are removed after the context ends; it does not work on your real documents.
  • The print() expressions display a checkable outcome. Print values and exception names are not substitutes for the program result itself.

Expected Output


filename,size_bytes

The output is the observable result of the sample operation. Compare its value and type with the explanation, not just whether the program runs.

Important Details and Edge Cases


If the report is opened in spreadsheet software, consider spreadsheet formula injection when filenames come from untrusted sources.

Before applying this to real documents, check whether the method reads data, creates a new file, moves it, or overwrites an existing file. Work in a disposable test directory first and handle OSError-related failures in applications.

Second Example: A Useful Variation


import csv
from io import StringIO

result_stream = StringIO(newline='')
record_writer = csv.writer(result_stream)
record_writer.writerow(['filename', 'size_bytes'])
record_writer.writerow(['text file.txt', 24])
print(result_stream.getvalue().splitlines()[1])

csv.writer handles delimiters and field quotation instead of fragile string concatenation.

Variation Output


text file.txt,24

Practice: Try It Yourself


Add a third file containing non-ASCII text and compare character count with byte size.

Begin by copying the example into a separate practice file. Change one input at a time, run it again, and describe why the result changed. If the exercise writes or deletes files, keep it inside a temporary test folder.

Official Python Documentation


For the complete reference, see the Python standard library documentation.

Common Beginner Mistakes


  • Forgetting newline="" and causing extra blank records on some platforms.
  • Assuming filesize is a character count rather than the number of stored bytes.
  • Before applying this to real documents, check whether the method reads data, creates a new file, moves it, or overwrites an existing file. Work in a disposable test directory first and handle OSError-related failures in applications.

Key Takeaways


  • Produce a basic inventory of filenames and file sizes in a CSV report.
  • Use csv.writer() with a text file opened using newline="" and encoding="utf-8". Store relative filenames rather than paths to unrelated parts of the computer; do not assume rows will be returned in a stable order unless sorted.
  • Avoid this common pitfall: Forgetting newline="" and causing extra blank records on some platforms.
Share this resourceSend this page to someone who may find it useful.