0

so im looking for the correct variable that will end the while loop once the loop reaches the end of the file. Here is my code so far:

file_name = input("Please enter file name: ")

open_file = open(file_name,"r")

while ##variable## != "":
    line1 = open_file.readline()
    line2 = open_file.readline()
    line3 = open_file.readline()
    line4 = open_file.readline()

Lets say that my file that i opened looks like this:

Babbage, Charles
10.0   9.5    8.0  10.0
 9.5  10.0    9.0
85.0  92.0   81.0
Turing, Alan
10.0   8.0    6.0
10.0  10.0    9.0   9.5
90.0  92.0   88.5
Hopper, Grace
10.0  10.0    8.0
10.0  10.0    9.0   9.5
90.0  92.0   88.0

I need the loop to end as soon as it reads the last line, heres some pseudocode:

#Get first data
#while data is not sentinel
    #process the data
    #
    #
    #
    #
    #Get next data

Hopefully thats clear, i appreciate your help.

JediObiJohn
  • 79
  • 2
  • 8

3 Answers3

1

Use a for loop instead:

for line in open_file:
    #do stuff
    print(line)

From the Tutorial - Reading and Writing Files


If you are forced to use a while loop:
readline will return an empty string when it reaches the end of the file so you can make the sentinel an empty string.

sentinel = ''

Before the while loop read a line

line = open_file.readline()

Use line in the while loop condition

while line != sentinel:

At the bottom of the loop, read another line.

Even though there may be empty lines in the file, those lines should still contain an end-of-line character like "\n" so it won't be an empty string.

wwii
  • 23,232
  • 7
  • 37
  • 77
  • Unfortunately this needs to be a while loop per instruction of my professor. Is there a way to do this with a while loop and a sentinel ? – JediObiJohn Oct 31 '17 at 18:55
0

As stated above, a for loop is the simplest and best way to read from a file. Unlike Java or C, where you could easily craft a condition for a while loop that remains true only while there is still content left to be read from the file, it is more awkward to do so in Python.

Files in Python expose an iterator, thus you can iterate over them using a for loop (most natural). You could also use the built-in next() method, as such:

f = open('abc.txt','r')
while(True):
    try:
        line = next(f)
        print(line,end='')
    except:
        break
vasia
  • 1,093
  • 7
  • 18
0

Of course this isn't optimal but to use a while loop use the Function I have in the comments:

def file_len(fname):
with open(fname) as f:
    for i, l in enumerate(f):
        pass
return i + 1



file_name = input("Please enter file name: ")

numOfLines = file_len(file_name)
open_file = open(file_name,"r")

count = 0
while count != numOfLines:
    #enter code here
    count += 1
Pintang
  • 438
  • 4
  • 17