7 File Handling

Author

Jacques Mock Schindler

Published

10.09.2025

To edit text files in Python, we write a function that assigns the content of a file to a variable as a string.

def file_reader(path : str) -> str:

    with open(path, mode='r', encoding='utf-8') as f:
        text = f.read()

    return text

To write encrypted or decrypted text to a file in Python, we write a function that writes a string to a file.

def file_writer(path : str, text : str) -> None:
    i = 0
    grouped_text = ""
    for c in text:
        i += 1
        if i % 50 == 0:
            grouped_text += c + "\n"
        elif i % 5 == 0:
            grouped_text += c + " "
        else:
            grouped_text += c
        
    with open(path, mode='w', encoding='utf-8') as f:
        f.write(grouped_text)

To ensure that texts consist exclusively of ASCII uppercase letters, we write a function that converts all lowercase letters to uppercase and converts all umlauts to their equivalent letters. All other characters are removed.

To have all methods for processing strings available, the string module must first be imported.

import string
def text_cleaning(text : str) -> str:
    clean = text.upper() \
                .replace('Ä', 'AE') \
                .replace('Ö', 'OE') \
                .replace('Ü', 'UE') \
                .replace('ß', 'SS') \
                .replace(' ', '') \

    cleaned_text = ''

    for c in clean:
        if c.isalpha():
            cleaned_text += c
    
    return cleaned_text