Skip to content

Python Read File Line by Line | ReadLines | Examples

  • by

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 the 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 a file path with a name or only a 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 the open() function. Then using for loop to get the value line by line. The readlines() function returns an array( Lists ) of the 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 return 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

[WpProQuiz 2]

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading