In this article, we’ll take a look at how to read a text file in python and also see the different ways to read a file.

How to read a text file in Python:

Depending on our requirement we can read a file in different ways, here we will see in three different ways.

1.Read entire file content at once:

The read() method is used to read the entire file content at a time.

def read_file():

    with open('D:\\work\\sample.txt', 'r') as f:
        print(f.read())

if __name__ == '__main__':
    read_file()

Output:

Hello
I am reading 
from Python Program

2.Read line by line through for-in loop:

Reading file line by line using for-in loop.

def read_file():

    with open('D:\\work\\sample.txt', mode='r') as f:
        for line in f:
            print(line, end='')


if __name__ == '__main__':
    read_file()

Output:

Hello
I am reading 
from Python Program

3.Read line by line using readline():

readline() method is used to read a file line by line.

def read_file():
    with open('D:\\work\\sample.txt') as f:
        lines = f.readlines()
    print(lines)


if __name__ == '__main__':
    read_file()

Output:

['Hello\n', 'I am reading \n', 'from Python Program']

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment