Read file upto nth index in python 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:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!