Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use readline to read txt file python3

Tags:

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?

like image 749
Code971 Avatar asked Mar 09 '15 06:03

Code971


People also ask

How do you read a text file row by row in Python?

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.

How do you read a single line of a text file in Python?

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.


1 Answers

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.

like image 130
Jon Clements Avatar answered Sep 20 '22 15:09

Jon Clements