5 Different ways to read a file line by line in Python

Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to read a file line by line in Python.

We have one  file intro1.txt in our directory and we want to read it line by line.Lets see how will we do that.

Using readlines()

readlines() we can use for small file. It reads all files details from memory, then  separate into lines and returns all in a list.  All the List returned by readlines or readline will store the newline character at the end.

Lets take an example,

fileHandler = open ('c:\\new folder\intro1.txt', "r")
# Get list of all lines in file
listOfLines = fileHandler.readlines()
for line in listOfLines:
    print(line.strip()) 
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

So in above example we have seen that listOfLines = fileHandler.readlines() this will return a list of lines in file. We can iterate over that list and strip() the new line character then print the line .

Above case is only use for small file for large file we have to look up some other methods because it use lots of memory.

Using readline()

For working with large file we have readline().It will read file line by line instead of storing all at one time.Also, if the end of the file is reached, it will return an empty string.

fileHandler = open ("c:\\new folder\intro1.txt", "r")
while True:
    
    line = fileHandler.readline()
    # If line is empty then end of file reached
    if not line :
        break;
    print(line.strip())
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
 Python supports modules and packages, which encourages program modularity and code reuse.

Using context manager (with block)

If we open any file it is very important to close that file,if we did not close then it will automatically close but sometime when there is  large function which not going to end soon.In that case we take help of context manager to cleanup and closeup.

fileHandler = open("c:\\new folder\intro1.txt", "r")
line = fileHandler.readline()
for line in fileHandler:
    print("Line{}: {}".format(count, line.strip()))
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py 
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

After termination of loop file will automatically close,even if there is any exception it will also terminates.

 Using context manager (with block)get List of lines in file

listOfLines = list()        
with open("c:\\new folder\intro1.txt", "r") as file:
    for line in file:
        listOfLines.append(line.strip()) 
    print(listOfLines)

Output:

['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.', 
"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.", 
'Python supports modules and packages, which encourages program modularity and code reuse.']

So in above example we have iterate all the lines in file and create a list.

Using context manager and while loop read contents of file line by line

So in this method we are going to use while loop and context manager for reading of any file.So in while loop we can give any condition according to this it iterate over lines in file.

with open("c:\\new folder\intro1.txt", "r") as fileHandler:  
    # Read next line
    line = fileHandler.readline()
    # check line is not empty
    while line:
        print(line.strip())
        line = fileHandler.readline()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
 Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. 
Python supports modules and packages, which encourages program modularity and code reuse.

Conclusion:

So in this article we have shown you different methods to read any file.Hope you enjoyed the session.