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?
Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.
Python readline() is a file method that helps to read one complete line from the given file. It has a trailing newline (“\n”) at the end of the string returned. You can also make use of the size parameter to get a specific length of the line.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With