Home »
Python
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?
Submitted by IncludeHelp, on December 17, 2019
File read() Method
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:
file_object.read(size)
Parameter(s):
- 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).
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
myfile.read()...
C++ is a popular programming language.
myfile.read(10)...
C++ is a p
myfile.read(-1)...
C++ is a popular programming language.
TOP Interview Coding Problems/Challenges