Python Forum

Full Version: why is this not filling my empty list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Could someone tell me why this isn't filling my empty list?
# creating empty list to read in file
    responses = []

    file = open("8_Ball_responses.txt" , "r")

    for line in file:
        responses.append((file.readline()).rstrip('\n'))

    file.close()

    print(responses[random.randint(0, len(responses) - 1)])
It's hard to say without seeing the file. However, file.readline() conflicts with file. The for loop already read the line for you, and put that into the variable line. So just append that:

for line in file:
    responses.append(line.strip())
So I pulled out the readline part of the code to read
# creating empty list to read in file
    responses = []

    file = open("8_Ball_responses.txt" , "r")

    for line in file:
        responses.append(line.rstrip('\n'))

    file.close()

    print(responses[random.randint(0, len(responses) - 1)])
It is still leaving an empty list.
Here is a copy of what is in the text file. The path is correct, the text file is in the same directory.

Yes, of course!
Without a doubt, yes.
You can count on it.
For sure!
Ask me later.
I'm not sure.
I can't tell you right now.
I'll tell you after my nap.
No way!
I don't think so.
Without a doubt, no.
The answer is clearly NO.
It's working find for me. Instead of that last line I would use random.choice:

print(random.choice(responses))
But I didn't change that before running the code and it worked. Given that your code is indented, and there is no import for random, I'm guessing that's a part of a larger program. Is this code in a function?
Yes, it is part of a larger program. Yes, it is part of a function. I can not use random.choice because we have not used that in class.

import random


def main():
    # creating empty list to read in file
    responses = []

    file = open("8_Ball_responses.txt" , "r")

    for line in file:
        responses.append(line.rstrip('\n'))

    file.close()

    print(responses[random.randint(0, len(responses) - 1)])

    print(responses)


main()

It works now. I had left out the calling of the function thinking if I just ran the code snippet it would still work. Thank you!!