+4 votes
in Programming Languages by (77.2k points)

How can I read all the lines of a file in a list in Pythonic way?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use list() or readlines() to read all the lines of a file in a list.

Here is an example:

with open('fltest.txt', 'r') as f:

    print(f.readlines())

OR

with open('fltest.txt', 'r') as f:
    print(list(f))

The contents of the file 'fltest.txt' are as follows:

This is the first line
This is the second line
This is the third line
This is the fourth line

The output of the code will be as follows:

['This is the first line\n', 'This is the second line\n', 'This is the third line\n', 'This is the fourth line']


...