Python read file line by line with example


Python provides inbuilt functions to create, write and read files. In this post, let's see how we can read a file line by line in Python.

Using readline()

It is recommended to read a file line by line especially for larger files instead of reading all the data. readline() method returns the next line in file as a string which will contain newline at the end and also if end of the file is reached, it returns an empty string.

Syntax

linetxt = fileHandler.readline([size])

Here, size is optional

Example

# Open a file
fp = open("test.txt", "rw+")

# consider below is the content of the file test.txt
# line1
# line2
# line3
# line4

linestr = fp.readline()
print "File content by readline: %s" % (linestr)

linestr = fp.readline(2)
print "File content by readline with size 2: %s" % (linestr)

# Close opend file
fp.close()

If you run the above program, results look like below:

File content by readline: line1
File content by readline with size 2: li