How to read a text file in python

With the help of python file handling methods, you can perform multiple operation in file like reading a file in python, writing file in python and updating file in python. In this super easy tutorial, you will learn how you can read text file in python.

Introduction: Read text file in python

How to read a text file in python

Python have in-built function for file handling. To read text file in python, you need to perform three simple task.

  • open file
  • read file
  • close file

Let suppose, we have a file called kekmart.txt in same directory and we want to read the content of that file.

kekmart.txt

Kekmart is cake delivery App
Download this App from Playstore
Service is only available in mumbai

Example: Reading text file using read() methods.

k=open("kekmart.txt", "r")
#reading all the text file
k.read()
#reading first 2 line
k.read(2)
k.close()

Example: Reading text file using readline() methods.

k=open("kekmart.txt", "r")
#reading all the text file
k.readline()
#reading first 2 line
k.readline()
k,readline()
k.close()

Explanation: Read text file in python

To read kekmart.txt file in python, we have to first open the file using open() method of file handling.

The open() method takes two parameters, first is file location and another one is the mode.

There are three main modes in python r, w, a.

  • r mode: The r mode is for reading file in python. We are using this mode to read our kekmart.txt file.
  • w mode: The w mode is used for writing text in python.
  • a mode: The a mode is used for the purpose of appending.

Syntax: open() method

open("file path","mode")

Once the file is open using open() method, now you can read text in file in python using read() and readline() file handling function.

Syntax: read() method

read()

The read method by default read all the text and you can also specify the line number to read the text at specify line number.

read(3)

Syntax: readline() method

The readline() methods in python, read single text line of file.

readline()

Writing two time readline(), will read two text line of file.

readline()
readline()

Syntax: close() method

close()

The last one is the close method, which is used for closing the file in python.

Conclusion: Reading text file in python.

  • Python had in-build file handling methods for reading text file in python.
  • To read text from file in python you have to perform three step open the file, read the file and close the file.
  • For reading text we have two methods read() and readline().

Was this article helpful?
YesNo

1 thought on “How to read a text file in python”

  1. Pingback: Buy Backlinks

Leave a Comment