22

I been working on this for hours and I cant get it right, any help would be appreciated! My question is how do I use the function .readline() to read until the end of a text file? I know that .readlines() work as well but I'm trying to process one line at a time.

Here's what I have for my code so far:

    a = open("SampleTxt.txt","r")

    While True:

        a.readline()

My problem is that I get an infinite loop when I run this, shouldn't it have stopped once it couldn't read a line any more?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Code971
  • 325
  • 1
  • 2
  • 4

1 Answers1

35

a.readline() will return '' an empty string when no more data is available, you need to check that and then break your while, eg:

while True:
    line = a.readline()
    if not line: 
        break

If it's not purely for learning purposes then you really should be using a with statement and for-loop to process the file, line by line:

with open('SampleTxt.txt') as fin:
    for line in fin:
        pass # do something

It's more clear as to your intent, and by using the with block, the fileobj will be released on an exception or when the block ends.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280