Reading history

Python File Handling: Read, Write and Append Files

4 min read 1 views

Learn Python file handling: open() modes, the with statement, reading line by line, appending, JSON and CSV files, and handling missing files.

Programs lose their variables when they stop. To keep data such as settings, scores or logs, you write it to a file and read it back later. Python’s built-in open() handles text files, and the standard json and csv modules handle structured data. This lesson covers file modes, the with statement, reading line by line, and handling a missing file.

In this lesson you will learn

  • How to open files in read, write and append mode
  • Why with open(...) is the safe way to work with files
  • Three ways to read a file
  • How to save and load JSON and CSV data
  • How to handle a file that does not exist

Writing, Appending and Reading Text

import os, tempfile

path = os.path.join(tempfile.mkdtemp(), "notes.txt")

with open(path, "w", encoding="utf-8") as f:
    f.write("Line one\n")
    f.write("Line two\n")

with open(path, "a", encoding="utf-8") as f:
    f.write("Line three\n")

with open(path, encoding="utf-8") as f:
    print(f.read(), end="")

with open(path, encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())

print(os.path.exists(path))

Output

Line one
Line two
Line three
1 Line one
2 Line two
3 Line three
True
  • The example writes into a temporary folder so it does not leave files behind. In your own code a plain name like "notes.txt" works.
  • "w" creates the file, or wipes it if it already exists. "a" adds to the end. With no mode, Python opens the file for reading ("r").
  • with open(...) as f: closes the file automatically when the block ends, even if an error happens inside it.
  • write() does not add newlines; include \n yourself.
  • Looping over the file object reads one line at a time, so even very large files fit in memory. strip() removes the trailing newline.
  • Passing encoding="utf-8" keeps non-English text such as Bangla readable on every operating system.

File Modes

ModeMeaningIf the file is missing
"r"Read (default)FileNotFoundError
"w"Write, replacing the old contentsCreates it
"a"Append to the endCreates it
"x"Create; fail if it existsCreates it
"b"Binary, added to another mode: "rb", "wb"Depends on the other letter

Ways to read: f.read() returns the whole file as one string, f.readline() returns the next line, and f.readlines() returns a list of lines.

JSON, CSV and Missing Files

import csv, json, os, tempfile

folder = tempfile.mkdtemp()

data = {"name": "Core Tech ED", "lessons": 20, "free": True}
json_path = os.path.join(folder, "site.json")
with open(json_path, "w") as f:
    json.dump(data, f)
with open(json_path) as f:
    print(json.load(f)["lessons"])

csv_path = os.path.join(folder, "marks.csv")
with open(csv_path, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "marks"])
    writer.writerows([["Rafi", 81], ["Nila", 92]])
with open(csv_path, newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["marks"])

try:
    open(os.path.join(folder, "missing.txt"))
except FileNotFoundError:
    print("File not found, handled safely")

Output

20
Rafi 81
Nila 92
File not found, handled safely
  • json.dump() / json.load() save and restore dictionaries and lists. JSON is the standard format for settings and web APIs.
  • csv.writer writes rows of a spreadsheet; csv.DictReader reads each row as a dictionary keyed by the header. Open CSV files with newline="" to avoid blank lines on Windows.
  • Catching FileNotFoundError lets the program give a clear message instead of crashing. See Exception Handling.

Common Mistakes

  1. Opening with "w" when you meant "a", which erases the existing contents.
  2. Forgetting to close the file. Use with and it is never an issue.
  3. Relative paths. "data.txt" is looked up in the folder you ran Python from, not necessarily the script’s folder.
  4. Writing numbers directly. f.write(5) fails; write str(5) or use JSON.

Practice Exercises

Exercise 1. Count the lines in a text file.

Show answer
with open("notes.txt", encoding="utf-8") as f:
    print(sum(1 for _ in f))

Exercise 2. Save a list of names to names.json and load it back.

Show answer
import json
with open("names.json", "w") as f:
    json.dump(["Rafi", "Nila"], f)
with open("names.json") as f:
    print(json.load(f))

Frequently Asked Questions

How do I check whether a file exists?

Use os.path.exists(path) or pathlib.Path(path).exists(). Often it is simpler to try opening it and catch FileNotFoundError.

What is the difference between text and binary mode?

Text mode reads and writes strings and handles encodings and newlines. Binary mode ("rb", "wb") reads and writes raw bytes, which you need for images, PDFs and other non-text files.

Summary

  • with open(path, mode) as f: is the safe pattern for files.
  • "r" reads, "w" overwrites, "a" appends.
  • Loop over the file to read it line by line.
  • Use json and csv for structured data.

Next: Python Modules.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *