Hi, I need some help to make a program where python reads each line(a string) of a .txt file.

-sample txt file-(EOF stands for 'End of File)
I need it to be able to read up to 300 students.

ID , Last , First, Lecture, Tutorial, A1, A2, A3, A4, A5
10034567, Smith, Winston, L01, T03, 6, 5.5, 8, 10, 8.5
10045678, Lee, Bruce, L02, T05, 4.5, 6.5, 7, 7, 8.5
00305678, Obama, Jack, L01, T05, 10, 10, 9, 9.5, 10
00567890, Brown, Palin, L02, T03, 4, 7.5, 6.5, 0, 5
10012134, Harper, Ed, L01, T03, 10, 9, 7.5, 10, 6.5
EOF

My problem is when I run the program, it doesn't stop!

Here's what I've done so far.

file = open ('grade.txt', 'r')

s=file.readline()
while s!="EOF":
    lst=s.split(',')
    print(lst)
    s=file.readline()

print(s)

Dani AI

Generated

Your loop kept running because there isn’t a literal line that says EOF in a plain text file — the file simply ends and the iterator stops. was right to suggest using a file iterator and with for safety; ’s list-comprehension is compact for quick tests. For a reliable, maintainable solution that easily converts rows into usable records and handles up to 300 students, use Python’s csv tools and convert the score fields to numbers as you read.

import csv
from itertools import islice

def load_students(path, max_students=300):
    students = []
    with open(path, newline='', encoding='utf-8-sig') as fh:
        reader = csv.DictReader(fh, skipinitialspace=True)
        for row in islice(reader, max_students):
            if not any(row.values()):           # skip empty lines
                continue
            row = {k.strip(): (v.strip() if v is not None else v) for k, v in row.items()}
            for col in ('A1','A2','A3','A4','A5'):
                if col in row:
                    try:
                        row[col] = float(row[col]) if row[col] != '' else None
                    except (ValueError, TypeError):
                        row[col] = None
            students.append(row)
    return students

If your file has no header, pass fieldnames=[...] to DictReader. Use encoding='utf-8-sig' to drop a BOM if present. To compute each student’s average after loading:

for s in students:
    scores = [s.get(k) for k in ('A1','A2','A3','A4','A5') if isinstance(s.get(k), float)]
    s['average'] = sum(scores) / len(scores) if scores else None

This approach makes data validation (missing or malformed scores), limiting to 300 entries, and downstream processing (sorting, averaging, exporting) straightforward. Check the original CSV for inconsistent commas, extra whitespace, or different decimal formats before bulk-processing.

Recommended Answers

All 4 Replies

I think that if you actually open up the file grade.txt, you'll see that there is no actual line with the text EOF on it; rather, in the example given, the EOF stands in the for the actual end-of-file marker, which isn't a printable character.

In any case, Python provides an easy way to iterate through a text file without using readline() or any explicit test for completion, by using just a for: loop:

inFile = open('grade.txt', 'r')
for line in inFile:
    lst = line.split(',')
    print(lst)
inFile.close()

Another way to do this, which may prove even more useful, is to use the with statement. Let's try that, with a little more formatting to the output as well:

with open('grade.txt', 'r') as inFile:
    for line in inFile:
        lst = line.split(',')
        for element in lst:
            print("{0:<15}".format(element.strip()),  end=' ')
        print()

The major advantage of the with is that you don't need to explicitly close the file.

I could also add that files of this type (called a comma-separated value file or CSV file), are especially common, so much so that Python has a special library just for handling the data from them.

, thank you SO MUCH!

how would i convert the output to a list? I was thinking of putting it inside a def function then converting it to a list from there, but unsure how?

how would i convert the output to a list?

with open('grade.txt') as in_file:
    lst = [i.split(',') for i in in_file]
print(lst)

If you don't want new line(\n),use i.strip().split(',')

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.