Account
Categories

read() Method


Definition:

When you use this method in a program, it reads characters from a file.

If you pass a number as a parameter, it reads only that many characters; otherwise, it reads all characters from the file.

Syntax:

file_object.read(size)

Example:

file = open("file1.txt", "r")

content = file.read(12)

print(content)

file.close()

Suppose file1.txt contains:

Rahul Kumar
Priya Sharma

Output:

Rahul Kumar
Pr

Exercise

Create a file named file1.txt and use the read() method to read the first 5 characters from the file.