In this lesson we will study Python readline() method required for reading a text file.
This method returns a line of characters, including the newline character, which is the \ n character.
Python readline() – first example
Let’s take a first example on an address book file that contains the following example contacts:
Name: cristina – Telephone: 3567
Name: coding – Telephone: 34789
We open the file using the open function, specifying the reading mode (r). Then we apply Python readline() method and try to print the read text.
f = open ('address_book.txt', 'r') contact = f.readline() print(contact) f.close()
The following code will print the first line only: Name: cristina – Telephone: 3567.
As we can see, the execution of readline() produces the reading up to the newline character, that is \ n.
Ultimately this method uses a cursor that represents a numeric index starting from 0 and increasing by 1 for each character read.
If we try to run readline() again we will read the second line, as the index has been increased.
f = open ('address_book.txt', 'r') contact = f.readline() print(contact) contact = f.readline() print(contact) f.close()
But clearly this code for reading a text file is not ideal. Let’s try using a loop.
Python readline() – second example
We reason that we will stop reading when we encounter the null string, as it represents the end of the file.
So let’s implement a possible solution:
f = open ('address_book.txt', 'r') contact = f.readline() while contact != "": print(contact) contact = f.readline() f.close()
We note that each contact in the address book will occupy two lines as the print function adds an additional newline character.
To avoid this problem we could use the print function with the end parameter, like so:
print (contact, end = “”), alternatively you can use the rstrip() method.
For in loop
An alternative to using readline in Python to be able to read a file is the for in loop.
Let’s see a simple example:
f = open ('address_book.txt', 'r') for contact in f: print(contact.rstrip()) f.close()
Ultimately we are treating the file as if it were simply a list of strings.
In this lesson we studied Python readline() method for reading data from a text file. We have also seen that it is not the only way to be able to read a text file.