AySeven
AySeven

Reputation: 63

Why am I getting string out of range index error within my list?

So I'm creating an 8 ball program that prompts the user for a question will then spit out a response. The project I have states that the answers must be in txt file, so I created this

file = open("Ball_response.txt","w")

file.write("YES, OF COURSE!")
file.write("WITHOUT A DOUBT, YES")
file.write("YOU CAN COUNT ON IT.")
file.write("FOR SURE!")
file.write("ASK ME LATER")
file.write("I AM NOT SURE")
file.write("I CAN'T TELL YOU RIGHT NOW?")
file.write("I WILL TELL YOU AFTER MY NAP")
file.write("NO WAY!")
file.write("I DON'T THINK SO")
file.write("WITHOUT A DOUBT, NO.")
file.write("THE ANSWER IS CLEARLY NO")

file.close()

The I want to call the list here

import random 

# Reading the Ball_response file
def main():
    input_file = open('Ball_response.txt', 'r')
    line = input_file.readline()
    print(line[0])

main()

But when I run the program, it only prints out "Y". I want

   0 -  Yes, Of Course
   1 -  Without a Doubt, yes
   2 -  You can count on it

etc..... How can I accomplish this? I feel like there is something I'm not understanding

Upvotes: 2

Views: 85

Answers (3)

永劫回帰
永劫回帰

Reputation: 692

In order to get each response on a different line you need to change the way you are writing your file.

file = open("Ball_response.txt","w")

file.write("YES, OF COURSE!\n")
file.write("WITHOUT A DOUBT, YES\n")
// etc

file.close()

Then in your function main since you want to print the whole line you need to do print(line).

import random

def main():
    input_file = open('Ball_response.txt', 'r')
    rand_idx = random.randrange(12)

    for i,line in enumerate(input_file):
      if i == rand_idx:
        print(str(i) + " - " + line.strip('\n'))

This will print (for example):

7 - I WILL TELL YOU AFTER MY NAP

Upvotes: 2

Morse
Morse

Reputation: 9134

You might want to fix your code first.

While writing into file add \n in each file.write so that all lines go to new lines like this

file.write("YES, OF COURSE!\n")

For more efficiency store all these strings in a list and use file.writelines(list)

lines = ["YES, OF COURSE!\n","WITHOUT A DOUBT, YES\n","YOU CAN COUNT ON IT.\n"]

file.writelines(lines)

For reading a file line by line do this.

def main():
    input_file = open('Ball_response.txt', 'r')
    i = 0
    for line in input_file:
        print(str(i) + ' ' + line)
        i = i+1

One can also do this to automatically enumerate

for i,line in enumerate(input_file):
    print(str(i) + ' ' + line)

Output will be like

0 YES, OF COURSE!

1 WITHOUT A DOUBT, YES

2 YOU CAN COUNT ON IT.

Upvotes: 1

Zack Tarr
Zack Tarr

Reputation: 851

You should use print(line) instead of print(line[0]). You are only getting Y because it is the [0]'th element in the string.

Upvotes: 0

Related Questions