Python Read File Line by Line | ReadLines | Examples

In python, you can read The text from a text file using inbuilt methods. Python Read File Line by line text from the file is comes under the FileHandling. You have to use an open class (function) to get a file object than with file object can use Readline() function or other function for reading a file line by line.

Python Read File Line by Line ReadLine Examples

Syntax

fileObj=open("filname","mode")
content=fileObj.readlines() #returns a array of lines.

The open() function needs two parameters first is filename then another mode. The filename will be file path with a name or only file name. A mode as per required operation on the file.

Modes

Here is a detail of File Handling mode in python.

Open for reading plain text
Open for writing plain text
Open an existing file for appending plain text

There are more modes available to handle a file, follow this tutorial – Python File Handling Introduction.

Python Read File Line by Line Example

Pass the file name and mode (r mode for read-only in the file) in open() function. Then using for loop to get the value line by line. The readlines() function returns an array( Lists ) of line, we will see the next example.

fileObj = open("testFile.txt", "r")

for line in fileObj.readlines():
    print(line)
fileObj.close()

Output:  EyeHunts

Python

Another Example to see return readlines() 

A retrun value of readlines() function is lists(Array) with \n.

File screenshot

Python Read File Line by Line Example
fileObj = open("testFile.txt", "r")

content = fileObj.readlines()
print(content)

Output: [‘EyeHunts\n’, ‘Python\n’, ‘Tutorial’]

QA: How to read a complete text file line by line using Python?

Here is another way to read file line by line in Python.

with open('testFile.txt') as fp:
    line = fp.readline()
    lineNumberCount = 1
    while line:
        print("Line {}: {}".format(lineNumberCount, line.strip()))
        line = fp.readline()
        lineNumberCount += 1

Output: Line 1: EyeHunts Python Tutorial
Line 2: Python read file line by line

Python File Handling Quiz

Python File Handling to test your knowledge – ( Create, Open, Update, delete and more about in Python)
It’s for Beginners, Advanced and Experienced Programmers.

Do comment if you have any suggestions and doubts on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of File Reading are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.