Reading and writing text files

One common task of a program is to read from or write to a file. Perhaps you want to save the high scores of the game your making, or you are creating a to-do task app, or a contacts list, or a chat application of some sort…

Fortunately Python makes it quite easy. A few examples that you can adapt for your own purposes.

### File: files.py

def read(filename):
    # Will return a list of strings, one for each line in the file.
    data = []
    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            data.append(line.replace("\n", ""))
    return data

def write_list(filename, data):
    # Takes a list of strings, will write it to the file, one per line.
    if isinstance(data, list):
        with open(filename, "w", encoding="utf-8") as w:
            for datum in data:
                w.write(datum + "\n")

def write_string(filename, data):
    # Takes a string and writes it to the file
    if isinstance(data, str):
        with open(filename, "w", encoding="utf-8") as w:
            w.write(data + "\n")
### File: main.py

import files

# Write list to a file
starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]
files.write_list("starwars.txt", starwars)

# Read list from a file
from_file = files.read("starwars.txt")
for item in from_file:
    print(item)

Exercise: Hangman game

Use file functionality to create a simple text-based hangman game!

On my Python website https://pbaumgarten.com/python, you’ll find links to a couple of files for this exercise:

As a reminder, the following will generate a random number from 0 to 100.

from random import randint
r = randint(0, 100)

To build this exercise, you will need to successfully complete the following:

# To help you get started, the following function will return a string that can be used to show the length of the secret word and the correct guesses.

def getSecretWordHint( secretWord, lettersGuessed ):
    hint = ""
    for letter in secretWord:
        if letter in lettersGuessed:
            hint = hint + letter
        else:
            hint = hint + "_"
    return hint

# Example usage

guesses = ["A","B","C","D","E"]
hint = getSecretWordHint("SECRET", guesses)
print( hint )

Have fun and good luck!

By the way, just before we finish the section on reading/writing files, you may have wondered what the “r” or “w” in the open() function meant. This instructs Python how we want to access the file we request. The different modes for opening a file are as follows: