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)

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.

@Schol-R-Lea, 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.