by R4R Team

- read() is a python function which read the file.

Syntax-

fileobject.read(index)

-Here fileobject is the object that points to the file location.
-index is allows read() function to read text only upto index value.
-Bydefault if we do not specify the index, then read() function read full file.

Example-
content in file is - "This is my string "
then read(4) will return 'This'
and read(10) will return 'This is my'


program-

#open a file and write
f=open('myfile.txt','w')
f.write("This is my string")
f.close()

#read only 4 character
f=open('myfile.txt','r')
print(f.read(4))
f.close()

#read only 10 character
f=open('myfile.txt','r')
print(f.read(10))
f.close()

#read only 13 character
f=open('myfile.txt','r')
print(f.read(13))
f.close()

#read only 20 character
f=open('myfile.txt','r')
print(f.read(20))
f.close()


output-

This
This is my
This is my st
This is my string


-In this program,firstly we write the text in the file.
-then we read only some character by read(number) and print them.




Leave a Comment: