How to read a text file line by line in python explained with examples

How to read a text file line by line in python

If you are looking for an explanation with examples on How to read a text file line by line in python, we have got your back. Here is a simplistic guide that will help you with it.

Well, we all know that python is a general-purpose advanced programming language and it has a lot of built-in functionality and features that you can easily use in your projects.

How to read a text file line by line in python?

The file system is one of the best built-in features in python.

The open() built-in function in python is very useful. You can open a file object with the help of this function either in a reading mode or in another mode.

We can pass multiple arguments in open() function but make it simple and focus on these two.

Open function syntax

fp  = open(‘full path of the file’,’ mode’)

Now let’s understand it in details :

The fp is normally a file pointer variable.mode is reading mode or writing mode.


Here we open a file in reading mode

 fp = open(‘example.txt’,’r’)

[su_label type=”success”]Suggested read[/su_label]  Hand-picked list of Python Ide for Beginners

File operation Modes in python :

  • r: reading mode.
  • w: writing-mode.
  • a: append mode.
  • rb: reading binary data.
  • wb: writing binary data.

The close() built-in function in python is also very necessary. With the help of this function, you can close your open file.

Because once you performed read or write operation into the file you have to close it so that resources allocated to your operation will be free for other operations.

Instead of calling and take a headache of close() function, you can simply write your code like this.

 with open(‘example.txt’,’r’) as fp

with is a keyword in python. that takes care of your open() and close() functionality at the same time. It performs an operation in this manner.


             fp = open(‘example.txt’,’r’)

             # perform your operation

    finally : 


Now after opening the file to read the file line by line

The object of the file that returned by open() function mainly has three methods.

  1. read()
  2. readline()
  3. readlines()

For reading the data from the file.

  • read() – This method reads the data from the file in a single text string. It is suitable for small files where you have to do some text manipulation.
  • readline() – This method is a very useful method for reading the text from the file line by line.

It will read one line and then another line separately. So you can read only a small amount of text with this method but if you want to read more text then you can simply pass the maximum number of bytes that you want to load at the same time.

For example :

              with open(‘example.txt’,’r’) as fp:

                 text = fp.readline()

                 count = 1

            while text:

            print (“Line {} : {}” .format(count,text.strip() ))

             text = fp.raedline()

             count = count + 1

[su_label type=”success”]Suggested read[/su_label] Why is Golang better than Java and Python

Code explanation

The above code will open a file in reading mode and store its object reference in the file pointer variable fp.

Then we call the method readline() which is responsible for reading file line by line and we print each and every line with the help of a while loop.


Line 0: Lorem ipsum dolor sit amet, consectetur adipiscing elit

Line 1:  sed do eiusmod tempor incididunt ut labore et dolore Magna aliqua

Line 2: Ut enim ad minim Veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat

Line 3: Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur

Line 4: Excepteur sint occaecat cupidatat non-proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Line 5:

Line 6 : Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC

Line 7: "Sed ut perspiciatis unde Omnis site Natus error sit voluptatem accusantium doloremque laudantium

Line 8: …………………..

Now, this is fine but there is another way also that helps you to read data from the file line by line.the method is more elegant also.

    with open(‘example.txt’,’r’) as fp:

       for count,  text in enumerate(fp):

     print (“Line {} : {}”.format(count,text))

In this usage, we are exploiting inherent Python usefulness. It permits us to repeat over the record object verifiably utilizing a for circle in the blend of utilizing the iterable article fp.

In addition to the fact that this is less difficult to peruse. It takes fewer lines of code to compose, which is consistently a best practice deserving of following.

Conclusion :

So in this article, we have seen a lot of built-in file system functionality in python and seen two major methods to read a text file line by line in python.

After passing the number of bytes as an input parameter in readline() function you can read as much data as you want.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top