Jose Pinto
Jose Pinto

Reputation: 121

How to read a file line-by-line into a new list?

How do I read every line of a file in Python and store each line in a list?

I want to read the file line by line and append each line to a new list.

For example, my file is this:

    0,0,2
    0,1,3
    0,1,5

And I want to achive this :

[0,0,2]
[0,1,3]
[0,1,5]

I tryed with this but isn't given me the answer I wanted.

a_file = open("test.txt", "r")
list_of_lists = [(float(line.strip()).split()) for line in a_file]
a_file.close()
print(list_of_lists)

Upvotes: 1

Views: 969

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

  • Use a with statement to ensure the file is closed even if there's an exception.

  • Use split(',') to split on commas.

  • You need a double loop, one to iterate over lines and another to iterate over the numbers in each line.

with open("test.txt", "r") as a_file:
    list_of_lists = [
        [float(num) for num in line.strip().split(',')]
        for line in a_file
    ]
print(list_of_lists)

Output:

[[0.0, 0.0, 2.0], [0.0, 1.0, 3.0], [0.0, 1.0, 5.0]]

Upvotes: 3

Related Questions