Read a Text File in Python Tutorial Example

20-Dec-2022

.

Admin

Read a Text File in Python Tutorial Example

Hi Dev,

In this tute, we will discuss Read a Text File in Python Tutorial Example. you can see python program to read text file. I would like to share with you how to read text file in python as string. step by step explain how to read text file in python.

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

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

#Python