Reading data from txt file only reads last line [closed]

The problem is that you are over-writing the value of namelist and scorelist with each pass through the loop. You need to add each item to a list. Adding a sequential list of items to a list is usually done with list.append() or a list comprehension. Read the documentation, or do some tutorials?

To actually create list, you can do this:

namelist, scorelist = [],[]
for li in data:
    namelist.append(li.split(":")[0])
    scorelist.append(li.split(":")[1])

Alternately, this might be a better overall approach:

        with open("Class1.txt", "r") as text_file:
            names_scores = [(e[0],e[1]) for e in [li.split(":") for li in text_file]

        for name,score in name_scores:
            print(name,score)

This assumes you really just want to extract the names and scores and print them, not do anything else. How you handle and store the data depends a lot on what you are doing with it once you extract from the file.

Browse More Popular Posts

Leave a Comment