Python Tutorial Python Advanced Python References Python Libraries

Python - File read() Method



The Python 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 returns the read content.

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

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

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

#read the file
MyFile = open("test.txt", "r")
print(MyFile.read())
MyFile.close()

The output of the above code will be:

This is a test file.
It contains dummy content.

Example: Read the partial file

The read() method can also be used to read the partial content of the file. This can be achieved by specifying the number of bytes to read as shown in the example below.

#read the file
MyFile = open("test.txt", "r")
#reading first 10 bytes
print(MyFile.read(10))
#reading next 5 bytes
print(MyFile.read(5))
MyFile.close()

The output of the above code will be:

This is a 
test 

❮ Python File Handling Methods