You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何逐行读取文件并将每一行内容存入新列表

问题原因

你的代码逻辑顺序错误:首先对包含逗号的整行字符串调用float()转换,"0,0,2"这类带逗号的字符串无法直接转为浮点数,会直接抛出类型错误,无法得到预期结果。

正确实现代码

常规写法(可读性更高)

list_of_lists = []
# 用with管理文件对象,自动完成资源释放,无需手动调用close()
with open("test.txt", "r") as a_file:
    for line in a_file:
        # 去除行首尾空白后按逗号分割,逐个转数值类型后组装为子列表
        row = [int(num) for num in line.strip().split(',')]
        list_of_lists.append(row)

# 按预期格式逐行输出
for row in list_of_lists:
    print(row)

如果需要存储浮点类型数值,把代码中的int(num)替换为float(num)即可。

列表推导式简写版本

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

for row in list_of_lists:
    print(row)
运行效果

输入你给出的test.txt文件内容时,代码输出结果完全符合你的预期:

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

内容的提问来源于stack exchange,提问作者Jose Pinto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:09:00