Text File - read() Function


☞ It reads the entire file content as a single string.

☞ After reading the file, pointer goes to the end of the file.

 
#reading data from a text file 

def reading_data():
    f = open("demo.txt","r")
    s=f.read()      #storing data in the form of string 
    print(s)
    f.close()

reading_data()    #calling a function 

Passing number of characters to read().

 
#reading data from a text file 

def reading_data():
    f = open("demo.txt","r")
    s=f.read(5)      #read only first 5 characters 
    print(s)
    s=f.read(5)      #read next 5 characters and so on 
    print(s)
    s=f.read(5)      #if no character left then it will give no error i.e. empty string 
    print(s)
    f.close()

reading_data()