Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
In this lesson we will talk about Python readlines() method, which reads the entire text file and returns a list.
Python readlines() – first example
In this first example we will read our rubric.txt file using this readlines, let’s see what happens. So here’s a possible example:
f = open('address_book.txt', 'r') contact = f.readlines() print(contact) f.close()
Using print on the list will print all the data it contains. In our case it will print: [‘Name: cristina – Telephone: 3567 \ n’, ‘Name: luisa – Telephone: 34789’].
We can see that each element also contains end-of-line characters, that is ‘\ n’.
In order to then print each row individually we can use an iterative instruction. But since each element contains the newline character we can use end in the print function.
Here is a possible solution:
f = open('address_book.txt', 'r') contact = f.readlines() for row in contact: print(row, end=' ') f.close()
By running the code we will now see the data printed like this:
Name: cristina – Telephone: 3567
Name: luisa – Telephone: 34789
Python readlines() – second example
We can also specify the number of lines to be read. To do this, just specify a number within the readlines() method.
So let’s take a simple example:
f = open('address_book.txt', 'r') contact = f.readlines(1) for row in contact: print(row, end=' ') f.close()
By entering readlines(1), only the first contact will be printed: Name: cristina – Telephone: 3567
Obviously, in this case, the cycle would not be needed.
Attention, if the number of bytes returned is greater than the number then it will not print any more lines.
In fact, let’s try to replace the value 1 with 2: f.readlines (2), in this case the second line will not be returned.
Let’s try another file, for example number_random.txt which contains this data:
f = open('address_book.txt', 'r') contact = f.readlines(2) for row in contact: print(row, end=' ') f.close()
In this case we will print the first and second lines:
This is because the number of bytes returned does not exceed the value indicated in brackets.
In this lesson we have studied Python readlines() method and developed examples in order to better understand how it works.
Some useful links
Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
Sort dictionary in Python