I’m learning CS/Python on MIT’s Open Courseware. They want me to design a hangman game and have given me some preliminary code for importing a wordlist and generating a random word from there. This code on its own returns an error: “can’t have unbuffered text I/O.” Here’s the code:
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
The MIT course does not use Python 3.0, which I am using, so there may be a problem there; as you can see I’ve already updated “print” from a declaration to a function for compatibility with Python 3.0.
This error is thrown because you are trying to read a text file with buffering switched off (the third parameter set to 0):
Replace the above line with
and it should work.
From the python docs: