Make a list of lines from a file

It is possible to the place a lines in a file in a list, with each line representing a single item in a list. This is done using the readlines() method which takes each line from the file and stores it in a list.

Consider the following example:

with open('new_file.txt') as file:
    lines = file.readlines()

print(lines)

The output:

>>>
['Have a nice day!\n', 'You too!\n', 'Thanks!']
>>>

In the example above you can see that the readlines() method created a list with three elements of type string.

We can iterate over the list using the for loop:

i = 0
for line in lines:
    i += 1
    print("Line", i, "-", line.strip())

The output:

Line 1 - Have a nice day!
Line 2 - You too!
Line 3 - Thanks!

 

We’ve used the strip() method to strip the newline character (\n).
Geek University 2022