Reading lines

Sometimes, it is necessary to read the contents of a file by line-by-file. In Python, there are two options to do this: readline() and readlines():

  • readline(): As the name suggests, this in-built function enables reading one line at a time. Let's review this using an example:
       if __name__ == "__main__": 
# open text file to read
file = open('read_line.txt', 'r')

# read a line from the file
data = file.readline()
print(data)

# read another line from the file
data = file.readline()
print(data)

file.close()

When the preceding code snippet is executed (available for download as read_line_from_file.py along with this chapter), the read_line.txt file is opened and a single line is returned by the readline() function. This line is stored in the variable data. Since the function is called twice in this program, the output is as follows:

       I am learning Python Programming using the Raspberry Pi Zero. 

This is the second line.

A new line is returned every time the readline function is called and it returns an empty string when the end-of-file has reached.

  • readlines(): This function reads the entire content of a file in lines and stores each it to a list:
       if __name__ == "__main__": 
# open text file to read
file = open('read_lines.txt', 'r')

# read a line from the file
data = file.readlines()
for line in data:
print(line)

file.close()

Since the lines of the files is stored as a list, it could be retrieved by iterating through the list:

       data = file.readlines() 
for line in data:
print(line)

The preceding code snippet is available for download along with this chapter as read_lines_from_file.py.