Python provides the
readlines() method in order to read all lines and return them as a list in a single step. The readlines() method returns every line as an item in a list and the complete data is provided as a list.
readlines() Method Tutorial
The readlines() method has a very simple syntax. Generally, it is used without a parameter but the size parameter can be also specified. The readlines() method returns a list that contains every line as an item.
- FILE is an opened file which will read and returned as a list.
- SIZE is optional and used to specify the byte count to read.
Read All Lines As List
The readlines() method reads all lines and returns them as a list where every line is an item in the list. In order to read a file, it should be opened with the
open() method where read mode is enabled. But alternatively, the read+write mode can be used too.
f = open("cities.txt","r") cities = f.readlines() print(cities)
['london \n', 'ankara \n', 'istanbul \n', 'Newyork \n', 'Dublin \n', 'Berlin \n']
From the output, we can see that every end of line character is displayed too. “\n” is used to specify the end of the line.
Read Specified Range of Bytes
The readlines() method can be also used to read lines for the specified byte range or size. The number of bytes we want to read is provided to the readlines() method as a parameter. In the following example, we read 20 bytes from the specified file.
f = open("cities.txt","r") cities = f.readlines(20) print(cities)
['london 3\n', 'ankara 4\n']