Python file object provides the readline() method in order to read a single line from the opened file. The line read from the start to the end of the line with the new line character. The readline() method generally used with the text, XML, JSON, and text-related files. Using the deadline() method with the binary files may not work as expected.
readline() Method Syntax
The readline() method has the following syntax.
- FILE_OBJECT is the allready opened file object or identifier. This object is required to call readline() method.
- SIZE is the byte count read from the start of the current line. This parameter is optional. If not specified complete line read.
In the tutorial we will use the following file content. The file is named as example.txt.
This is the 1st line. This is the 2st line. This is the 3st line. This is the 4st line. This is the 5st line. This is the 6st line.
Read Line From File
The readline() simply reads the current line. When a file is opened a cursor is created with the file object. The cursor located at the start of the file and in every read it is located to the last read location. For example, if the first line is read the cursor is located at the start of the next line. The readline() method reads the complete line in every execution.
file = open("example.txt") line = file.readline() print(line) line = file.readline() print(line) print(file.readline() ) file.close()
This is the 1st line. This is the 2st line. This is the 3st line.
Read Specified Number of Characters From the Line
The readline() accepts parameter named size. We can specify the size we want to read which is the character count which read. In the following example we read 5 characters.
file = open("example.txt") line = file.readline(5) print(line) line = file.readline(5) print(line) print(file.readline(5) ) file.close()
'This ' 'is th' 'e 1st'