readline-method

(ii). readline(): In python programming, readline() method is used to read data from a file in single line format ie it reads only first line. The readline() method also takes numeric value as an argument. This numeric value defines that how many characters should be read.
If we leave it blank then it will read all data of first line.

Example 1 demonstrating the use of readline() method without argument and example 2 demonstrating the use of readline() method with argument passing.

Syntax:

#www.pythonlobby.com
f = open("file_name",'r')
f.readline(n) 
#or f.readline()

Example 1: For readline() method without argument.

readline-method-example

Explanation: The readline() method used to read only single line. Hence it returned only first line as output out of two line.

Example 2: For readline() method with argument.

readline-method-example-2

Explanation: We have opened our existing file named “test.txt” in ‘r’ mode. Using readline() method we read the first 15 character and stored it in z variable. Later we print the information stored in our variable ‘z’.

readlines-method

(iii). readlines(): In python programming, readlines() method is used to read complete data line by line from a file and that each line is stored in list format.

Syntax:

#www.pythonlobby.com
f = open("file_name",'r')
f.readlines()

Example 1: For readlines()

readlines-method-2

Explanation: Here total two lines are there in our text file. Using readlines() method both lines are fetched and stored in list format.