Python Read a Text File Example

Published On: 26/12/2022 | Category: Python


Hi Guys,

Today our leading topic is python read text file example. I would like to share with you python read file from directory. this example will help you how to read text file in python. We will look at example of how to read text file in python as string.

The three techniques listed below use the open() APIs to read text files.

  1. read():Read text file content as string.
  2. readline():Read single line from text file as string.
  3. readlines():Read all lines from text file as python list.

So let's see bellow example:

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 Tuts-Station.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 Tuts-Station.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 Tuts-Station.com!', 'This is body', 'Thank you']

It will help you....

Happy Pythonic Coding!