File handling (text and CSV files) using the CSV module; file modes: read, write, append

Python's open() hands you a file in one of three modes: r reads, w writes a fresh file (destroying the old one), a appends to the end, and the with statement closes it for you.

9 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Not everything lives in a database

ResultDesk keeps college.db for marks, but the world keeps sending plain files: an attendance log in notes.txt, mark sheets as .csv, error logs to write somewhere.

Before the csv module can parse commas (next lesson), you must hold the file itself: open it, read lines out, write lines in, close it without losing data.

Python does all of it through one function, open(), and one letter in it decides whether you read, write, or accidentally destroy.

Theory

Three ways to open a notebook

The same notebook, three intentions:

  • r: open to read, touch nothing. Notebook missing? You cannot read air: error.
  • w: tear out every page and start writing on page one. Missing? A new notebook is bought.
  • a: open at the last written page and continue below. Missing? New notebook, same behaviour.

The torn pages are the point to remember: mode w is a shredder with a pen attached.

At a glance

The file modes

ModeIf file existsIf file missing
r (read)Opens for readingFileNotFoundError
w (write)TRUNCATES to empty, then writesCreates new
a (append)Writes after existing contentCreates new
r+ (read+write)Opens for bothFileNotFoundError
b suffix (rb, wb)Binary mode (images, .db files)As per base mode

Practical

Read, write, append: the with pattern

# WRITE a fresh report (destroys any old report.txt!)
with open('report.txt', 'w') as f:
    f.write('DBMS average: 61.5\n')      # \n is YOUR job
    f.write('Maths average: 73.2\n')

# APPEND to a running log (never destroys)
with open('activity.log', 'a') as f:
    f.write('report generated\n')

# READ it back, line by line
with open('report.txt', 'r') as f:
    for line in f:                        # the file object is iterable
        print(line.strip())               # strip() removes the trailing \n

# other reading tools:
# f.read()       -> the whole file as one string
# f.readline()   -> one line
# f.readlines()  -> list of all lines

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

Why with, not open/close

You CAN write f = open(...) and later f.close(). Professionals almost never do, because the close is skipped the moment an error jumps over it, leaving files locked and writes unflushed.

with open('report.txt', 'w') as f: closes the file automatically, even if the block crashes. It is the file-handling equivalent of the transactions promise: cleanup that cannot be forgotten.

One more habit: every write() outputs exactly what you give it, no newline added. Line breaks are your job: '\n'.

Quiz

attendance.log holds a month of records. A script opens it with open('attendance.log', 'w') to add today's entry, writes one line, closes. What does the file contain now?

  1. Only today's line: mode w truncated the month of records at open time
  2. The month of records plus today's line at the end
  3. The month of records with today's line at the top
  4. Nothing: w mode requires the file to not exist
Show the answer

Only today's line: mode w truncated the month of records at open time

Mode w empties an existing file the instant it opens, BEFORE any write happens: the month of history was gone even if the script crashed right after open(). Adding to the end is exactly what a (append) exists for. This silent-truncation accident is the single most expensive beginner file bug: logs, reports and CSVs all die to it.

Think first

Predict the doubled gaps

report.txt has two lines. A student runs:

with open('report.txt') as f:

for line in f:

print(line)

Before tapping: how does the output look, and why?

Show the answer

Each line prints with a blank line after it. Every line read from a file keeps its trailing \n, and print() adds another: two newlines per line, doubled spacing.

Fix: print(line.strip()) (or line.rstrip('\n'), or print(line, end='')). Tiny detail, but it appears in nearly every write-the-output exam question about file loops. Also note: no mode given means 'r', the default.

Watch out

The three file-handling mark-losers

w when you meant a: history destroyed silently. Ask yourself before every open-for-writing: fresh file, or continuation?

Missing \n in write(): everything lands on one line; write() adds nothing.

r on a missing file: FileNotFoundError, unlike w/a which create. The exam table above IS the answer to "explain file modes": reproduce it with the exists/missing columns.

Theory

CSV files are just text files

Open marks.csv with this lesson's tools and you get honest text: 101,DBMS,78 per line. You could split(',') yourself... until a name contains a comma and your parser shatters. That is precisely why the csv module exists: same open(), same with, same modes, plus a parser that knows the format's edge cases. Next lesson: reader, writer, and their Dict cousins.

Summary

Key takeaways

  • open(name, mode): r reads (error if missing), w creates/TRUNCATES, a appends (creates if missing).
  • Mode w empties an existing file at open time: the silent destroyer.
  • with open(...) as f: closes automatically, even on errors: the professional default.
  • Lines read from files keep their trailing \n: strip() before printing; write() adds no newline.
  • read()/readline()/readlines()/iteration cover all reading styles.
  • CSV files are text files; the csv module adds comma-safe parsing on top.
  • Memory hook: read the notebook, shred-and-write, or continue on the last page.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python interaction with text and CSV

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

File handling (text and CSV files) using the CSV module; file modes: read, write, append · Database Handling using Python · Gri-Learn