Python - File read() Method


Advertisements

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.

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")
print(MyFile.read())

Output

Python is a programming language.
Learning Python is fun.

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")
#read first 33 bytes of the content
print(MyFile.read(33))

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

Output

Python is a programming language.

Learning

Python File Handling Methods
Advertisements