简体   繁体   English

如何将文件逐行读入新列表?

[英]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?如何在 Python 中读取文件的每一行并将每一行存储在列表中?

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.使用with语句确保即使出现异常也关闭文件。

  • Use split(',') to split on commas.使用split(',')以逗号分隔。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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