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!
You will need the following two files:
- words_list.txt - A list of common hangman words as a text file. Save it into your project folder.
- hangman_pics.py - Python code with a list of strings that you can use to “draw” your hangman character.
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:
- Load the words text file into a Python list
- Use the random number generator to randomly select one item from the list as the secret word
- Reveal the secret word hiding the letters not yet guessed (see below for sample code on this)
- Use a while loop to keep asking the player to guess a new letter
- If a guessed letter is not in the secret word, increase their wrong guesses count and draw the new hangman.
- If a guessed letter is in the word, add it to your list of correct guesses.
# 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:
r+opens for reading and writing (cannot truncate a file)
wfor writing (erasing it if it exist)
w+for writing and reading (erasing it if it exists)
rbfor reading a binary file. The file pointer is placed at the beginning of the file.
rb+reading or writing a binary file
wb+writing a binary file
a+opens for appending
ab+Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
xopen for exclusive creation, failing if the file already exists