Python File read() Method with Example

Python File read() Method: Here, we are going to learn about the read() method, how to read text of a file in Python programming language. By IncludeHelp Last updated : November 26, 2023

File read() Method

The read() method is an inbuilt method in Python, it is used to read the content of the file, by using this method we can read the specified number of bytes from the file or content of the whole file.

Syntax

The syntax of the read() method is:

file_object.read(size)

Parameter(s)

The parameter(s) of the read() method is/are:

  • size – It is an optional parameter, it specifies the number of bytes to be read from the file. It's default value is -1 that returns the content of the whole file.

Return value

The return type of this method is <class 'str'>, it returns the string i.e. file's content (if the file is in text mode).

read() Method: Example

# Python File read() Method with Example

# creating a file 
myfile = open("hello.txt", "w")
# wrting text to the file
myfile.write("C++ is a popular programming language.")
# closing the file
myfile.close()

# reading the file i.e. opening file in read mode
myfile = open("hello.txt", "r")
# reading & printing the whole file 
# Here, we are not specifying the size
print("myfile.read()...")
print(myfile.read())

# reset the position 
myfile.seek(0)

# reading 10 bytes and printing
print("myfile.read(10)...")
print(myfile.read(10))

# reset the position 
myfile.seek(0)

# reading whole file by passing -1
print("myfile.read(-1)...")
print(myfile.read(-1))

# closing the file
myfile.close()

Output

The output of the above example is:

myfile.read()...
C++ is a popular programming language.
myfile.read(10)...
C++ is a p
myfile.read(-1)...
C++ is a popular programming language.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.