简体   繁体   中英

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)
  • 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM