How To Read A File In Python?

Perusing text records in Python is generally simple to contrast and the majority of the other programming dialects. Typically, we simply utilize the “open()” work with perusing or composing mode and afterwards begin to circle the text documents line by line.

This is now the best practice and it can’t be any more straightforward ways. In any case, when we need to peruse content from different records, there is most certainly a superior way. That is, utilizing the “Document Input” module that is underlying to Python. It joins the substance from various records that permit us to process everything in a solitary for-circle and has a lot of different advantages.

In this article, I’ll show this module with models.

0. Without the FileInput Module

We should view the “customary” approach to perusing different text documents utilizing the open() work. Yet, before that, we want to make two example documents for showing reason.

with open(‘my_file1.txt’, mode=’w’) as f:

    f.write(‘This is line 1-1\n’)

    f.write(‘This is line 1-2\n’)

with open(‘my_file2.txt’, mode=’w’) as f:

    f.write(‘This is line 2-1\n’)

    f.write(‘This is line 2-2\n’)

In the above code, we open a document with the mode w which signifies “compose”. Then, at that point, we compose two lines in the document. If it’s not too much trouble, be seen that we really want to add the new line \n. Any other way, the two sentences will be written in a solitary line.

From that point onward, we ought to have two text documents in the current working registry.

Presently, suppose we need to peruse from both the message documents and print the substance line by line. Obviously, we can in any case do that utilization the open() work.

# Repeat through all document

for document in [‘my_file1.txt’, ‘my_file2.txt’]:

    with open(file, ‘r’) as f:

        for line in f:


Here we need to utilize two settled for-circles. The external circle is for the documents, while the inward one is for the lines inside each record.

1. Utilizing the FileInput Module

All things considered, nothing keeps us from utilizing the open() work. Notwithstanding, the fileinput module simply gives us a neater approach to perusing various text documents into a solitary stream.

Most importantly, we really want to import the module. This is a Python inherent module with the goal that we don’t have to download anything.

import fileinput as fi

Then, at that point, we can involve it for perusing from the two documents.

with fi.input(files=[‘my_file1.txt’, ‘my_file2.txt’]) as f:

    for line in f:


Since the fileinput module is intended for perusing from different documents, we don’t have to circle the record names any longer. All things considered, the information() work takes an iterable assortment type like a rundown as a boundary. Likewise, interestingly, every one of the lines from the two records are available in a solitary for-circle.

2. Utilize the FileInput Module with Glob

Once in a while, it may not be down to earth to have such a record name list with every one of the names that are physically composed. It is very normal to peruse every one of the documents from an index. Likewise, we may be just keen on specific kinds of records.

For this situation, we can utilize the glob module which is one more Python worked in module along with the fileinput module.

We can do a straightforward investigation before that. The os module can assist us with posting every one of the documents in the current working index.

It tends to be seen that there are many records other than the two text documents. In this manner, we need to channel the document names since we need to peruse the text records as it were. We can involve the glob module as follows.

from glob import glob


Presently, we can put the glob() work into the fileinput.input() work as the boundary. Thus, just these two text documents will be perused.

with fi.input(files=glob(‘*.txt’)) as f:

    for line in f:



3. Get the Metadata of Files

You might ask how might we realize which document precisely the “line” is from when we are perusing from the stream that is really joined with various records?

For sure, utilizing the open() work with settled circle is by all accounts exceptionally simple to get such data since we can get to the current document name from the external circle. Nonetheless, this is indeed a lot more straightforward in the fileinput module.

with fi.input(files=glob(‘*.txt’)) as f:

    for line in f:

        print(f’File Name: {f.filename()} | Line No: {f.lineno()} | {line}’)

It’s just plain obvious, in the above code, we utilize the filename() to get to the current document that the line comes from and the lineno() to get to the current record of the line we are getting.

4. At the point when the Cursor Reaches a New File

Aside from that, there are additional capacities from the fileinput module that we can utilize. For instance, imagine a scenario where we need to accomplish something when we arrive at another document.

The capacity isfirstline() assists us with concluding whether we’re perusing the primary line from another document.

with fi.input(files=glob(‘*.txt’)) as f:

    for line in f:

        if f.isfirstline():

            print(f’> Start to peruse {f.filename()}…’)


This could be exceptionally valuable for logging reason. Along these lines, we can be shown with the current advancement.

5. Leap to the Next File

We can likewise effectively quit perusing the current record and leap to the following one. The capacity nextfile() permits us to do as such.

Before we can demo this component, if it’s not too much trouble, let me re-compose the two example documents.

with open(‘my_file1.txt’, mode=’w’) as f:

    f.write(‘This is line 1-1\n’)

    f.write(‘stop reading\n’)

    f.write(‘This is line 1-2\n’)

with open(‘my_file2.txt’, mode=’w’) as f:

    f.write(‘This is line 2-1\n’)

    f.write(‘This is line 2-2\n’)

The main distinction from the first documents is that I added a line of text quit perusing in the primary text record. Suppose that we need the fileinput module to quit perusing the primary document and leap to the subsequent when it sees such substance.

with fi.input(files=glob(‘*.txt’)) as f:

    for line in f:

        on the off chance that f.isfirstline():

            print(f’> Start to peruse {f.filename()}…’)

        on the off chance that line == ‘stop reading\n’:




In the above code, another if-condition is added. Whenever the line text is quit perusing it will leap to the following record. Accordingly, we can see that the line “1-2” was not perused and yield.

6. Peruse Compress File Without Extracting

Here and there we might have packed documents to peruse. As a rule, we should uncompress them before we can peruse the substance. In any case, with the fileinput module, we might not need to extricate the substance from the packed records before we can understand it.

We should make up a packed text document utilizing Gzip. This document will be utilized for show purposes later.

import gzip

import shutil

with open(‘my_file1.txt’, ‘rb’) as f_in:

    with‘my_file.gz’, ‘wb’) as f_out:

        shutil.copyfileobj(f_in, f_out)

In the above code, we added the record my_file1.txt into a compacted document utilizing gzip. Presently, how about we perceive how fileinput can peruse it without additional means for uncompressing.

with fi.input(files=’my_file.gz’, openhook=fi.hook_compressed) as f:

    for line in f:


By utilizing the boundary openhook and the banner fi.hook_compressed, the gzip record will be uncompressed on the fly.

The fileinput module right now upholds gzip and bzip2. Sadly not the other arrangement.


In this article, I have presented the Python underlying module fileinput and how to utilize it to peruse various message documents. Obviously, it won’t ever supplant the open() work, however as far as adding various records to a solitary stream, I accept it is the best practice.

How To Generate A Random Number In Python?
How To Install Matplotlib Python?
How To Install Python On Windows?
How To Install Python?
How To Make A List In Python?
How To Print An Array In Java?
How To Print In Python?
How To Read A File In Python?

Latest Updates

Popular Articles

Related Articles

How To Call A Function In Python?

What are Python Functions? In this section, we initially discover the essentials of Python Functions,...

How To Add To A Dictionary Python?

Python word reference is one of the implicit information types. Word reference components are...

How Does Tiktok Algorithm Work?

TikTok is the web-based media sensation whose 'commonly recognized name status' simply continues to...

How Does The Youtube Algorithm Work?

Individuals all over the planet watch north of 1 billion hours of YouTube recordings...