Processing the Data in a Text File

50 min read Text Files

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

Processing the Data in a Text File

Most text-file programs follow one pattern: read the data, change or filter it, and write the result to a second file. A text file cannot be edited in the middle easily, so "deleting" a line means writing every other line to a new file.

# copy the lines that do not contain the letter "a" to another file
with open("source.txt") as src, open("result.txt", "w") as dst:
    for line in src:
        if "a" not in line.lower():
            dst.write(line)

Counting words or characters works the same way: split() breaks a line into words, and string methods test each character.

vowels = consonants = 0
with open("notes.txt") as f:
    for ch in f.read():
        if ch.isalpha():
            if ch.lower() in "aeiou":
                vowels += 1
            else:
                consonants += 1

Remember: open in "w" mode only the file you intend to replace. Opening the source file with "w" by mistake erases it before a single line is read.

Python exercise

The input is the content of source.txt. Write to an in-memory result.txt every line that does not contain the letter a (either case), then print the content of result.txt by going back to its start with seek(0) and calling read().

import io
import sys

src = io.StringIO(sys.stdin.read())   # open("source.txt")
dst = io.StringIO()                   # open("result.txt", "w+")
for line in src:
    dst.write(line)  # only the lines without an "a"
dst.seek(0)
print(dst.read().rstrip("\n"))

Log in to edit and run this code.