Text File - readline() Function


☞ It will read one line at a time.

☞ When EOL(End of Line) is reached, it will return empty string.

☞ After reading first line, pointer goes to the first character of the next line.

Example 1 : To show how to read lines

 
#reading lines from a text file 

def reading_data():
    f = open("demo.txt","r")
    s=f.readline()  #it will read first line
    print(s,end='')
    s=f.readline()  #it will read second line and so on
    print(s,end='')
    s=f.readline()  #if line doesn't exist return empty string but no error
    print(s,end='')
    s=f.readline()  
    print(s,end='')
    f.close()

reading_data()  

Example 2 : To overcome above reading lines problem as we don't know how many lines will be there in a file.

 
#reading lines from a text file 

def reading_data():
    f = open("demo.txt","r")
    s=f.readline()  #it will read first line
    while s!='':
        print(s,end='')
        s=f.readline()
    f.close()

reading_data()    

Example 3 : Other way to read lines using readline() function

 
#reading lines from a text file 

def reading_data():
    f = open("demo.txt","r")
    while True:
        s=f.readline()
        if s!='':
            print(s,end='')
        else:
            break
    f.close()

reading_data()  

NOTE :-Passing number of characters to readline() function will not give an error and it will also not give number of characters you need.