Python – Read Text File

Read Text File in Python

To read text file in Python, follow these steps.

  1. Call open() builtin function with filepath and mode passed as arguments. open() function returns a file object.
  2. Call read() method on the file object. read() returns a string.
  3. The returned string is the complete text from the text file.

Example 1: Read Text File

In the following Python program, we will open sample.txt file in read mode. We will read all the contents of the text file and print the text to the console.

Python Program

fileObject = open("sample.txt", "r")
data = fileObject.read()
print(data)

Output

Welcome to pythonexamples.org

You can provide the complete or absolute path to the open() function or provide a relative path if the base path is present in the PATH environment variable.

Example 2: Read only Some Characters in the Text File

If you need to read only specific number of characters, say N number of characters, present at the starting of the file, pass N (number) as argument to read() function.

In the following Python program, we will read first 20 characters in the file.

Python Program

f = open("sample.txt", "r")
data = f.read(20)
print(data)

Output

Welcome to pythonexa

read(20) function returned the first 20 characters from the text file.

Example 3: Read file in Text mode

read, write and execute modes are based on the permissions. There are text and binary based on the nature of content.

In the following example, we will open the file in text mode explicitly by providing “t” along with the read “r” mode.

Python Program

f = open("sample.txt", "rt")
data = f.read()
print(data)

Output

Welcome to pythonexamples.org

Example 4: Read Text File Line by Line

To read text line by line from a file, use File.readline() function. File.readline() returns the current line and updates its pointer to the next line. So, when you call readline() function for the next time, the next line is returned.

Remember that readline() returns the line along with the new line character at the end of the line, except for the last line. So, if you do not require the new line character, you may use strip() function. There is a catch here. If your line contains white space characters at the start and end, and if you use strip(), you will loose those white space characters in the line.

In this example, we shall read the text file line by line.

Python Program

#get file object
f = open("sample.txt", "r")

while(True):
	#read next line
	line = f.readline()
	#if line is empty, you are done with all lines in the file
	if not line:
		break
	#you can access the line
	print(line.strip())

#close file
f.close

Output

Hi User!
Welcome to Python Examples.
Continue Exploring.

Summary

In this tutorial of Python Examples, we learned how to read a text file in Python with the help of well detailed Python example programs.