Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python file read() method is used to read the content of the specified file. The method has an optional parameter which is used to specify number of bytes to read and return of the given file.

Syntax

file.read(size)

Parameters

size Optional. specify number of bytes to read and return. default is -1 which means the whole file.

Return Value

Returns the bytes read in string.

Example: Read the whole file

In the below example, Python file read() method is used to read the whole content of the file called MyFile.

MyFile = open("python_test.txt", "r")

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.

print(MyFile.read())

The output of the above code will be:

This is line 1 content.
This is line 2 content.
This is line 3 content.

Example: Read the partial file

In the below example, file handling read() method is used to read the partial content of the file called MyFile. This is achieved by using optional parameter called size of the method to specify number of bytes to read and return of the given file.

MyFile = open("python_test.txt", "r")

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.

#read first 23 bytes of the content
print(MyFile.read(23))

#read next 8 bytes of the content
print(MyFile.read(8))

The output of the above code will be:

This is line 1 content.

This is

❮ Python File Handling Methods