Use readline to read txt file python3

Code971 picture Code971 · Mar 9, 2015 · Viewed 48.1k times · Source

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?

Answer

Jon Clements picture Jon Clements · Mar 9, 2015

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.