I am learning Python and would be grateful for your advice on this problem.
I have written a program with some functions in it to implement a simple word search game (see code below). I was given a driver program which only works if my program has been correctly implemented. I tested all my functions with examples and they seemed to work correctly but when I run the driver program I get this error message
>>>
Traceback (most recent call last):
File "/Users/<name>/Documents/a3_driver.py", line 88, in <module>
words = a3.read_words(words_file)
File "/Users/<name>/Documents/a3.py", line 266, in read_words
fh = open(words_file)
TypeError: invalid file: None
I believe it relates to my second last function called read_words, but I cannot seem to work out the problem. Any feedback would be extremely appreciated, I have included the code for this function below (I've also included the last function as well called read_board as this is very similar and also reads a txt file, just in case i've made the same mistake twice). Thank you in advance
the driver program for the game can be downloaded from the bottom of this page: http://spark-public.s3.amazonaws.com/programming1/a3/a3.html
The read_words function creates a words list made up of the words from a file.
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
# A simple .txt file used in this function simply contains the 4 words below, each printed on a new line
CRUNCHY
COWS
EAT
GRASS
>>> read_words('wordlist1.txt')
['CRUNCHY', 'COWS', 'EAT', 'GRASS']
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
fh = open(words_file)
lst = []
for line in fh:
line = line.strip()
for i in line.split():
lst.append(i)
return lst
#print (lst)
fh.close()
The read_board function creates a board made up of the rows of letters from a file.
def read_board(board_file):
""" (txt file) -> list of list of str
# A simple txt file used in this example contains the following...
EFJAJCOWSS
SDGKSRFDFF
ASRJDUSKLK
HEANDNDJWA
ANSDNCNEOP
PMSNFHHEJE
JEPQLYNXDL
>>> read_board('board1.txt')
[['EFJAJCOWSS'], ['SDGKSRFDFF'], ['ASRJDUSKLK'], ['HEANDNDJWA'], ['ANSDNCNEOP'], ['PMSNFHHEJE'], ['JEPQLYNXDL']]
Return a board read from open file board_file. The board file will contain
one row of the board per line. Newlines are not included in the board.
"""
data = []
fh = open(board_file)
for line in fh:
items = line.rstrip('\r\n').split('\t') # strip new-line characters and split on column delimiter
data.append(items)
return data
fh.close()
words_fileis null (None).read_words(), its withwords_filefh.close()is after thereturn data, which is therefore not called.None, for a beginner that might not be so clear.fh = open(words_file), it complains:TypeError: invalid file: None. Ergo,words_fileisNone