File Handling in Python

Reading and writing files with open(), why with is not optional, and the mode letters that decide whether you keep your data.

5 minute read · Free · Taught properly in our Python Training in Amritsar

Files are read and written through open(). The important part is how you close them again.

Read a whole file

with open("notes.txt", "r") as f:
    content = f.read()
print(content)

The with block closes the file for you, including when the code inside raises an error. Without it you must call f.close() yourself, and on Windows a file left open cannot be renamed or deleted by anything else. Use with every time.

Line by line

with open("students.txt") as f:
    for line in f:
        print(line.strip())

This reads one line at a time instead of loading the file into memory, which matters the day someone hands you a 2 GB log. .strip() removes the newline at the end, and any stray spaces.

Writing

with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")

write() does not add a newline. You do.

The mode letters, and a warning

  • "r" — read. The default. Errors if the file does not exist.
  • "w" — write. Empties the file immediately, before you write anything.
  • "a" — append. Adds at the end, keeps what was there.
  • "x" — create. Errors if the file already exists.

"w" on a file with data in it destroys that data the moment open() runs, whether or not your write succeeds. When you mean "add to this", the letter is "a".

CSV, properly

Do not split on commas by hand — a field containing a comma inside quotes will break it:

import csv

with open("marks.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["marks"])

DictReader uses the header row for keys, so you get a dictionary per row.

Paths

from pathlib import Path

p = Path("data") / "marks.csv"
if p.exists():
    text = p.read_text()

pathlib joins paths correctly on Windows and Linux both, which string concatenation with "/" does not.

Stuck on this in your own code?

That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.