-2

I added an open file to my previously working code and now it's not doing what is supposed to.

I tested and ran for loop on an open file to see if everything is working and it did. It printed me a single list of all the words inside the txt file.

my expectation is to check if the word is in the words_list and continue, but now what happens is, it will always print (word is not in the list), even if I type the word that is indeed in the list.

words_list = []
with open("generated one column words.txt", "r") as f:
    reader = f.read()
    words_list.append(reader)

def main():
    used_words = []
    while True:
        word = input("Type 4 letter word: ")
        if not word.isalpha():
            print("Only letters are allowed!")
        elif word not in words_list:
            print("word is not in the list")
        elif len(word) == 4 and word not in used_words:
            used_words.append(word)
            print("good job, try another word")
        elif word in used_words:
            print("word already exists")
        elif len(word) != 4:
            print("word is not 4 letters long")
game = main()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Eurostyle
  • 1
  • 1
  • 3
    `words_list` isn't a list of words. It's a list with a single element, which is the whole content of the file. – jonrsharpe Aug 29 '19 at 14:37
  • `f.read()` will give you the whole contents of the file as a single string. So your `words_list` only has a single item, and `word in words_list` will only be true if you match the text of the entire file. You probably want to use [`str.split`](https://docs.python.org/3.7/library/stdtypes.html#str.split) followed by [`list.extend`](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), or maybe just `for line in file: append(line)` if you always only have one word per line. – 0x5453 Aug 29 '19 at 14:37
  • 1
    Possible duplicate of [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Mihai Chelaru Aug 29 '19 at 14:38

5 Answers5

0
with open("generated one column words.txt", "r") as f:
    words_list = f.read()

def main():
    used_words = []
    while True:
        word = input("Type 4 letter word: ")
        if not word.isalpha():
            print("Only letters are allowed!")
        elif word not in words_list:
            print("word is not in the list")
        elif len(word) == 4 and word not in used_words:
            used_words.append(word)
            print("good job, try another word")
        elif word in used_words:
            print("word already exists")
        elif len(word) != 4:
            print("word is not 4 letters long")
game = main()
galaxyan
  • 5,944
  • 2
  • 19
  • 43
0

You could use f.readlines() instead. Then you only have to get rid of the newline characters.

0

this line

elif word not in words_list:

should be

elif word not in words_list[0]:

words_list is a list with only 1 element at the [0] position. You have to specify the [0]

Calculus
  • 781
  • 7
  • 20
0
def main():

    # opening the file with one word per each line
    with open('generated one column words.txt', 'r') as f:
        # reading each lines without newline at the end
        words_list = [line.strip() for line in f.readlines()]

    # caching 4-letter word after submit
    used_words = list()

    while True:
        word = input('Type 4 letter word: ')
        if word.isalpha():
            if word in words_list:
                if len(word) is 4:
                    if word not in used_words:
                        used_words.append(word)
                        print('good job, try another word')
                    else:  # if word already added in used_words
                        print('word already exists')
                else:  # if length of word != 4
                    print('word is not 4 letters long')
            else:  # if word not in words_list
                print('word is not in the list')
        else:  # if word contains special characters or digits
            print('Only letters are allowed!')


if __name__ == "__main__":
    main()  # infinite run the function main()
0

Since you are using f.read(), it reads the entire file as a single string with each line separated by \n character that's why your query returns false every time. If your .txt file contains words-

this
that
there

your current code will read it as 'this\nthat\nthere' and words_list will have this single string which will look like- ['this\nis\nthat\nnear\nhome']. Modify your code to read the file as following and it will work:

words_list = []
with open("generated one column words.txt", "r") as f:
    for line in f:
        words_list.append(line.strip())

Or you can modify your own code as following-

words_list = []
with open("generated one column words.txt", "r") as f:
    reader = f.read()
    words_list.extend(reader.split('\n'))
yabhishek
  • 408
  • 4
  • 14
  • Thank you very much! Your first option worked like a charm and is now saved in my notes and in my brain! And thanks to everyone for their time helping me! – Eurostyle Aug 29 '19 at 15:34