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

读取含列表的文本文件计算行和报错:int与str无法相加

问题解决:读取文件中列表的列表求和报错

问题重现

读取test_list.txt文件(内容为[[3, 5, 7, 11, 13], [3, 5, 7, 11, 17], [3, 5, 7, 11, 19]])时,运行以下代码报错unsupported operand type(s) for +: 'int' and 'str',但把文件内容直接粘到代码里却能得到正确结果[39, 43, 45]:

with open('test_list.txt', 'r',) as f:
    data = f.read()
    row_sums = [sum(row) for row in data]
    print (row_sums)

原因分析

  • f.read()返回的是字符串类型,不是Python的列表对象。遍历这个字符串时,是逐个取每个字符(比如[、3、,),sum(row)里的row是单个字符串字符,和整数相加自然触发类型错误。
  • 直接把内容粘到代码里时,Python会自动将这段文本解析成列表对象,遍历的是里面的子列表,所以能正常求和。

解决方案

方案1:用ast.literal_eval解析(推荐)

ast.literal_eval能安全地把字符串形式的Python字面量转换成对应对象,不会执行恶意代码:

import ast

with open('test_list.txt', 'r') as f:
    # 把字符串解析成列表对象
    data = ast.literal_eval(f.read())
    row_sums = [sum(row) for row in data]
    print(row_sums)  # 输出 [39, 43, 45]

方案2:用eval(仅文件内容完全可控时用)

eval可以直接执行字符串代码,但如果文件内容被篡改,可能会运行危险代码,所以不推荐:

with open('test_list.txt', 'r') as f:
    data = eval(f.read())
    row_sums = [sum(row) for row in data]
    print(row_sums)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:38:09