How to read a text file in Python?

PythonServer Side ProgrammingProgramming

A text file is the file containing simple text. Python provides inbuilt functions to read, create and write text files. We will discuss how to read a text file in Python.

There are three ways to read a text file in Python −

  • read() − This method reads the entire file and returns a single string containing all the contents of the file .

  • readline() − This method reads a single line from the file and returns it as string.

  • readlines() − This method reads all the lines and return them as the list of strings.

Read a file in Python

Let there be a text file named “myfile.txt”. We need to open the file in read mode. The read mode is specified by “r”. The file can be opened using open(). The two parameters passed are the name of the file and the mode in which the file needs to be opened.

Example

file=open("myfile.txt","r")

print("read function: ")
print(file.read())
print()

file.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file

print("readline function:")
print(file.readline())
print()

file.seek(0) #Take the cursor back to beginning of file

print("readlines function:")
print(file.readlines())
file.close()

Output

read function:
This is an article on reading text files in Python.
Python has inbuilt functions to read a text file.
We can read files in three different ways.
Create a text file which you will read later.

readline function:
This is an article on reading text files in Python.

readlines function:
['This is an article on reading text files in Python.\n', 'Python has
inbuilt functions to read a text file.\n', 'We can read files in three
different ways.\n', 'Create a text file which you will read later.']

As clear from the output −

The read function() reads and returns the whole file.

The readline() function reads and returns only one line.

The readlines() function reads and returns all the lines as list of the strings.

raja
Published on 10-Jun-2021 13:37:37
Advertisements