简体   繁体   中英

IndexError : list index out of range when retrieving text from a file

I'm trying to create a quiz in python, and I need to retrieve more than one question from an external text file. I manage to retrieve the first question successfully, but I get the "list index out of range" error when trying to retrieve the second one.

This is what a fragment of my current code looks like.

if choice1 == "CH":
        choice2 = input ("Would you like to do the easy, medium or hard questions ?").lower()
        if choice2 == "easy":
            load_profile = open("chemistryquiz.txt","r")
            question1 = load_profile.read().splitlines()[4]
            print (question1)
            question2 = load_profile.read().splitlines()[5]
            print (question2)

The program works perfectly fine if I comment out anything regarding question 2. Where have I gone wrong ? PS, I checked the text file and I made sure the number of the line is 5, I am aware you start counting from 0 when programming in python.

Also, these are the contents of chemistryquiz.txt

Chemistry Quiz :

Easy :

1) What is the chemical symbol of Carbon ? A: C B: Ca
2) What is the weight of an electron ? A: 0 B: 0.1

Let's step through this:

load_profile = open("chemistryquiz.txt","r")

The file is open; and you have a file handle load_profile . The file bookmark is at the start of the file.

question1 = load_profile.read().splitlines()[4]

You have read the entire file, split it into lines, and assigned the 5th line to question1 .

print (question1)
question2 = load_profile.read().splitlines()[5]

Since the bookmark is still at the end of the file, read() returns only EOF. splitlines does nothing useful. There is no element 5. KABOOM! .


Go back to the text on reading lines from a file. For instance ...

with open("chemistryquiz.txt","r") as load_profile:
    for input_line in load_profile:
        # This loop will give you the file, one line at a time.

Thye problem is that you're calling load_profile.read() multiple times. Each time you call this, it starts reading from where any previous file reading functions left off. But the first call read the entire file, so the second call has nothing left to read. It returns an empty string, and splitlines() returns an empty list.

Just read the file once.

lines = load_profile.read().splitlines()
question1 = lines[4]
question2 = lines[5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM