CoachFullStack

Python Guide #11: Reading Files

Python lets you read files, write to files and create files. In this guide I show you how to read files, perform simple operation on the data and then we will improve game of hangman we made before.

To read a file, we use open

with open("path_to_file", "r") as f:
    data = f.read()

This is the simplest way to read files, if you want to have more, then I recommend you start going to documentation, I can’t present everything, but enough to get you started.

Improving hangman game.

It is time for us to improve a hangman game. Instead of providing the word ourselves and seeing it, now we will create file which contains words, that the program will choose from. Then we will play against computer, based on a database of its words.

To start, lets create a file, in which we will put our words. In the directory of the project, create new file dictionary.txt.

Inside of dictionary, lets put words, that we want computer to have access to, one line, one word.

apple
orange
cheery
horse
crocodile
kangaroo
chicken
motorbike
yacht

Now lets experiment with reading the file, create new python program in the same directory

with open("dictionary.txt", "r") as f:
    d = f.read()

print("Initial data:\n", d)
# Now we want to separate data,
# so that we have list
# of words
# that we can iterate over
l = d.split("\n")
# function split, splits string
# in the places where
# provided character is
print(l)
# We want to get rid of whitespaces
# and empty words
final_list = []
for i in range(len(l)):
    if l[i]:
        # append adds
        # element to list
        final_list.append(l[i])
print(final_list)

Now you know how to read file, how to process its contents to generate a list and from previous guide, you know how to use random function. Lets use these skills to improve hangman game.

Instead of taking user input as a guess word, it will take random word from a text file.

import random
# Lets give player 5 chances,
# you can modify this later if you want
chances = 5

with open("dictionary.txt", "r") as f:
    d = f.read()

l = d.split("\n")
final_list = []

for i in range(len(l)):
    if l[i]:
        final_list.append(l[i])

word_to_guess = random.choice(final_list)
game_finished = False
failed_letters = ""
# functions len() returns length of an object
current_state = "_" * len(word_to_guess)

def update_state(letter):
    '''
    This function takes a letter as parameter
    and replaces underscore in current state
    in places where this letter should be
    '''
    new_state = ""
    for i in range(len(word_to_guess)):
        if word_to_guess[i] == letter:
            new_state += letter
        else:
            new_state += current_state[i]
    return new_state

# as long as game is not finished
# we want the cycle to repeat
# ask for letter
# update state
# evaluate chances
while not game_finished:
    print(current_state, "chances remaining", chances, "\nincorrect letters:\n", failed_letters)
    letter = input("Please input letter: ")

    # checking if letter is inside the word to guess
    # if it is right, we update the word
    # if not, we remove chance
    if letter in word_to_guess:
        current_state = update_state(letter)
    elif letter in failed_letters:
        print("You already used this letter!")
    else:
        failed_letters += letter
        chances -= 1
    
    # if current guessed word matches
    # word we need to guess
    # game is finished and we win
    if current_state == word_to_guess:
        print("Congratulations, you guessed the word:", word_to_guess)
        game_finished = True
    
    # if we have no chances left
    # we lost, game is finished
    # loop won't repeat
    if chances == 0:
        game_finished = True
        print("Word has not been guessed:", word_to_guess)

Compare what has changed and try to understand it. Now the game became challenging. You can also add more words to the dictionary.



Next: Python Guide #12: Writing to Files

Previous: Python Guide #10: Importing Modules