• Register

Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). In this article, we are going to study about reading line by line from a file.

read the lines - there is a clue here somewhere :

The easiest way is to use the readlines() function on the open file. That does exactly what you want - it creates a new list and puts every line of the file into that list.

file_lines =[] 
with open(the_file, 'r') as the_file: 
     for line in the_file: 
         # process the line in some way  
         file_lines.append(line) 

 answer gives a full code fragment to do that.

If you want to process every line before storing it - you can do this :

file_lines =[] 
with open(the_file, 'r') as the_file: 
     for line in the_file: 
         # process the line in some way  
         file_lines.append(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. We can iterate over the list and strip the newline '\n' character using strip() function.

Example:

# Python code to 
# demonstrate readlines() 

L = ["Geeks\n", "for\n", "Geeks\n"] 

# writing to file 
file1 = open('myfile.txt', 'w') 
file1.writelines(L) 
file1.close() 

# Using readlines() 
file1 = open('myfile.txt', 'r') 
Lines = file1.readlines() 

count = 0
# Strips the newline character 
for line in Lines: 
	print("Line{}: {}".format(count, line.strip())) 

 

And that is the beauty of Python - an open file behaves like a list of lines which can be looped around.

1,760 points
6 1