Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Read Files

Reading a file is as common as writing one: a program loads its settings, a list of words, a table of data or yesterday's results. You open the file in read mode, which is the default, and either read it all at once or go through it line by line. The examples first write a small file so they have something to read.

Reading the whole file

with open("poem.txt", "w") as f:
    f.write("Twinkle, twinkle, little star,\nHow I wonder what you are.\n")

with open("poem.txt") as f:
    text = f.read()
print(len(text), "characters")
print(text.upper(), end="")
Output
58 characters
TWINKLE, TWINKLE, LITTLE STAR,
HOW I WONDER WHAT YOU ARE.

read() returns the whole file as one string, including the new line characters. It is simple and fine for small files.

Reading line by line

A file object is iterable: a for loop gives one line at a time, which also works for files far bigger than the computer's memory. Each line still ends with \n, so strip it before use:

with open("marks.txt", "w") as f:
    f.write("Asha 91\nRavi 78\n\nMeera 85\n")

total, count = 0, 0
with open("marks.txt") as f:
    for number, line in enumerate(f, start=1):
        line = line.strip()
        if not line:
            continue                  # skip empty lines
        name, mark = line.split()
        print(f"line {number}: {name} has {mark}")
        total += int(mark)
        count += 1
print("Average:", round(total / count, 1))
Output
line 1: Asha has 91
line 2: Ravi has 78
line 4: Meera has 85
Average: 84.7

readlines() returns all lines as a list, and read().splitlines() gives the lines without their line endings.

CSV files

Tables are often stored as CSV (comma-separated values) files, which spreadsheets can open and save. The csv module reads them correctly, even when a value contains a comma inside quotes. DictReader gives each row as a dictionary keyed by the header line:

import csv

with open("people.csv", "w", newline="") as f:
    f.write('name,city,age\nAsha,Pune,21\n"Rao, Ravi",Delhi,25\n')

with open("people.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], "|", row["city"], "|", int(row["age"]) + 1)
Output
Asha | Pune | 22
Rao, Ravi | Delhi | 26

csv.writer and csv.DictWriter write CSV files in the same way.

When the file is missing

Opening a file that does not exist raises FileNotFoundError. Catch it with try and except to give a clear message, or check first with os.path.exists.

Practice exercises

  1. Write a file with five words, one per line, then read it and print the words in alphabetical order.
  2. Count the lines, words and characters of a text file.
  3. Read a CSV file of products and prices and print the total price.
  4. Try to open a file that does not exist and print a friendly message instead of a traceback.