1

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)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Jose Pinto
  • 121
  • 4
  • 1
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – ranban282 Oct 31 '21 at 17:44

1 Answers1

3
  • 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]]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578