How to Read a Text File in Python?

By Hardik Savani October 30, 2023 Category : Python

Hello,

Now, let's see an example of python read text file example. you can see python read txt file example. you will learn python read file from directory. step by step explain how to read text file in python. So, let's follow a few steps to create an example of how to read text file in python as string.

There are three following methods to read text file with open() functions.

read(): Read text file content as string.

readline(): Read single line from text file as string.

readlines(): Read all lines from text file as python list.

Without any further ado, let's see the below code examples below one by one.

You can use these examples with python3 (Python 3) version.

Example 1: using read()

main.py

# Python read text file using read()
with open('readme.txt') as f:
    contents = f.read()
  
print(contents)

Output:

Hi ItSolutionstuff.com!
This is body
Thank you

Example 2: using readline()

main.py

# Python read text file using readline()
with open('readme.txt') as f:
    content = f.readline()
  
print(content)

Output:

Hi ItSolutionstuff.com!

Example 3: using readlines()

main.py

# Python read text file using readlines()
with open('readme.txt') as f:
    contents = f.readlines()
  
print(contents)

Output:

['Hi ItSolutionstuff.com!', 'This is body', 'Thank you']

I hope it can help you...

Tags :
Shares