Text Files · 4 / 17 Theory

Processing the content of a file

Once you know how to read and write, the exercises consist of transforming what was read. These are the patterns that repeat.

Transforming line by line

with open("in.txt", "r", encoding="utf-8") as src, open("out.txt", "w", encoding="utf-8") as dst:
    for line in src:
        dst.write(line.upper())

Change what you do with line and you get another program: .lower(), .title(), .replace("a", "e")… The line already brings its \n and it is kept when writing it.

If the transformation needs to work with the text without the break (for example, reversing it), it is removed and put back:

for line in src:
    dst.write(line.rstrip("\n")[::-1] + "\n")

If the \n were not removed before reversing, the line break would end up at the beginning of the line. It is the key detail of Reverse text from a file.

Encrypting: shifting letters

ord(c) gives the number of a character and chr(n) the character of a number. With that you can shift each letter a fixed number of positions (Caesar cipher):

def encrypt(text, shift):
    result = ""
    for c in text:
        if "a" <= c <= "z":
            result += chr((ord(c) - ord("a") + shift) % 26 + ord("a"))
        elif "A" <= c <= "Z":
            result += chr((ord(c) - ord("A") + shift) % 26 + ord("A"))
        else:
            result += c            # spaces, numbers, signs: unchanged
    return result

print(encrypt("Hello, Zoe", 3))   # Khoor, Crh

The % 26 makes it go back to a after z. You will use it in Encrypt a text file, applying the function to each line.

Counting

with open("in.txt", "r", encoding="utf-8") as f:
    text = f.read()

print(len(text.splitlines()))   # lines
print(len(text.split()))        # words
print(len(text))                # characters

Searching

query = input()
for line in lines:
    if query in line:
        print(line)

in checks whether one string is inside another. If you want to ignore upper and lower case, convert both with .lower().

Paging: a counter inside the loop

Programs such as more show a fixed number of lines and wait for the user to press a key:

counter = 0
with open("story.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip("\n")[:79])   # cut long lines to 79 characters
        counter += 1
        if counter % 24 == 0:            # every 24 lines
            input()                      # wait for the user to press Enter

counter % 24 == 0 is true on line 24, 48, 72… It is the idea of More program.

Recommendation: work incrementally

First check that you read correctly (print(line)), then add the transformation, and finally write to the output file. If something fails, you will know at which step.