Reading and Writing Text Files

55 min read Text Files

This is a free course. Log in to run the code exercises and track your progress.

Reading and Writing Text Files

Writing: write(s) writes one string and returns the number of characters written; writelines(list_of_strings) writes every string in the list. Neither adds a newline for you.

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

Reading:

  • read(): the whole file as one string; read(n): the next n characters.
  • readline(): the next line, including its \n; an empty string at the end of the file.
  • readlines(): a list of all the remaining lines.
  • A file object is iterable: for line in f: reads it line by line without loading it all.

tell() returns the current position (the number of characters read or written so far, for plain text); seek(0) moves back to the start.

with open("poem.txt") as f:
    print(f.readline(), end="")   # Twinkle twinkle little star
    print(f.tell())               # 28
    f.seek(0)
    print(len(f.readlines()))     # 3

A classic board question: count the lines that start with a given letter.

count = 0
with open("poem.txt") as f:
    for line in f:
        if line.startswith("T") or line.startswith("t"):
            count += 1
Python exercise

The input is the content of a text file, read into an in-memory file. Count the lines that begin with T or t and print the count, then print the total number of words in the file.

import io
import sys

f = io.StringIO(sys.stdin.read())   # stands in for open("poem.txt")
t_lines = 0
words = 0
for line in f:
    pass  # update t_lines and words
print(t_lines)
print(words)

Log in to edit and run this code.