Python Forum
why is this not filling my empty list? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: why is this not filling my empty list? (/thread-15548.html)



why is this not filling my empty list? - Siylo - Jan-21-2019

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)])



RE: why is this not filling my empty list? - ichabod801 - Jan-21-2019

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())



RE: why is this not filling my empty list? - Siylo - Jan-21-2019

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.


RE: why is this not filling my empty list? - ichabod801 - Jan-21-2019

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?


RE: why is this not filling my empty list? - Siylo - Jan-21-2019

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!!