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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.