I am creating a function for a words game and I need to create a word list made up of the words from a file called wordlist.txt. My first thought was to open that file firstly and pass the open file as an argument to the function Im am trying to create. But lastly I realized that my funtion it supossed to return a list of all words with the newlines removed from the open file words_file.(It is that can even possible in python?). On the others each line Each line of the file contains a word in uppercase characters from the standard English alphabet but this I think I got it by using upper() and.split().
I am terrily stuck it in this. Any help will be useful. Thank you so much in advance.
PS: I found this structure looking for any information about this kind of read file. words_file = askopenfile(mode='r', title='Select word list file') Coul be useful in this case anyway?
This is my function structure:
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
file = open("C:\Python34\wordlist.txt", "r")
return words_file.read(wordlilst.txt).replace("\n", "").upper().split()
I'm assuming you want to use the parameter
words_file as the source of your file. Your code ignores it, assigns a hardcoded file to
file, then tries to call
read on the non-existing parameter.
I think this might be what you wanted:
def read_words(words_file): words_list =  # initialize empty word list with open(words_file) as file: # open the file specified in parameter # 'with' makes sure to close it again for line in file: # iterate over lines words_list.append(line.replace("\n", "")) # add every line to list # ^ remove trailing newline, which iterating includes return words_list # return completed list
To run it for your file, use
read_words("C:\Python34\wordlist.txt"), which will return the list.