---
title: "Reading and Writing Files, Including CSV"
description: "Opening a file, reading it line by line or writing to it, and closing it again, plus the row-and-column shape of CSV. This is where a program's data starts outliving the run that produced it."
canonical: https://lightmysky.com/learn/computing/reading-and-writing-files-including-csv-mt_j5qb4FdkdI
source: https://lightmysky.com/learn/computing/reading-and-writing-files-including-csv-mt_j5qb4FdkdI.md
retrieved: 2026-11-12
---

> **Agent view.** This is the Markdown twin of the page, for tools and assistants.
> When to use this site, and the call that answers each job: https://lightmysky.com/agent-instructions.md
> API description (OpenAPI 3.1): https://lightmysky.com/openapi.json · Authentication: https://lightmysky.com/auth.md
> Pricing: https://lightmysky.com/pricing.md · Catalog: https://lightmysky.com/llms.txt · Full catalog: https://lightmysky.com/llms-full.txt
> Every machine-readable file on this domain: https://lightmysky.com/.well-known/ai-catalog.json
> Ask for Markdown with `Accept: text/markdown`, a `.md` address, or `?mode=agent`.

# Reading and Writing Files, Including CSV

Opening a file, reading it line by line or writing to it, and closing it again, plus the row-and-column shape of CSV. This is where a program's data starts outliving the run that produced it.

Subject: Computing · Area: Programming · Ages 17 to 18
Page: https://lightmysky.com/learn/computing/reading-and-writing-files-including-csv-mt_j5qb4FdkdI

## Ready when they can

- Read a text file line by line and build a result from it
- Write records to a CSV file and read them back into objects or dictionaries
- Say what closing a file does, and what a relative path depends on

## Lesson: Files that outlive your program

open(path, mode) returns a file object. Mode 'r' reads an existing file; 'w' creates or truncates one; 'a' appends.

close() flushes buffered output and releases the resource. flush() can also flush output but leaves the file open. A with block closes its file on exit. Flushing does not by itself guarantee durable physical storage.

**Example.** readline() reads the next line. Iterating over a text file also reads lines in order. This loop builds a total from scores.txt containing 7 and 2 on separate lines:
```python
with open("scores.txt", "r") as f:
    total = 0
    for line in f:
        total += int(line)
```
The total is 9. Each converted line is added to the running result.

*(drawing: Reads advance the position. read() returns remaining text; readlines() returns remaining lines as a list.)*

A relative path such as data.txt is resolved against the process's current working directory, which can differ from the script's folder. An absolute path starts from a filesystem root. A subfolder path can still be relative. Saved data remains in the file after the run ends; a fresh run must read it into new variables.

**Example.** CSV separates fields with commas. Quoting allows commas or line breaks inside a field, so a physical line need not be a record. csv.reader removes enclosing CSV quotes and returns strings: "Oak, red" becomes Oak, red.
```python
import csv
with open("books.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["name", "pages"])
    w.writeheader()
    w.writerow({"name": "Oak, red", "pages": 8})
```

**Example.** Read the saved records using their headers, then reconstruct numeric values:
```python
with open("books.csv", "r", newline="") as f:
    records = list(csv.DictReader(f))
for row in records:
    row["pages"] = int(row["pages"])
```
DictReader initially gives string values. int restores the page count's numeric type. Printing f itself shows file-object details, not its contents.

A text line may retain its final newline. If only that newline should be removed, line.rstrip('\n') removes trailing newline characters while preserving spaces. Unrestricted strip() also removes surrounding whitespace, which may be meaningful. Text-file write() does not add a newline automatically; include '\n' when the format needs one.

**Recap.** Choose the file mode, track the read position and close the resource. Resolve relative paths from the current working directory. Use CSV tools and reconstruct value types.

*File-operation teaching adapted from the Introduction to Python Programming chapter 14 corpus records, with corrected path and buffering explanations and independently written CSV examples and assessments.*

## Practice

8 questions on this page, each with its working shown.

## Needs first

- [Designing with Objects: Deciding What Each Class Owns](https://lightmysky.com/learn/computing/designing-with-objects-deciding-what-each-class-owns-mt_De_gpvpOzg)

## Opens up

- [Exceptions: Raising, Catching and Recovering](https://lightmysky.com/learn/computing/exceptions-raising-catching-and-recovering-mt_hEVa1JRrGu)
- [Relational Databases: Tables, Keys and Relationships](https://lightmysky.com/learn/computing/relational-databases-tables-keys-and-relationships-mt_i7pZV6H902)
- [File Systems: Names, Blocks and Metadata](https://lightmysky.com/learn/computing/file-systems-names-blocks-and-metadata-mt_jN4u3idvF3)
- [Cleaning Real Data: Missing, Duplicated and Wrong](https://lightmysky.com/learn/computing/cleaning-real-data-missing-duplicated-and-wrong-mt_qIsLXA-7EC)
