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

读取文本文件数据到列表时触发TypeError错误求解决方案

解决读取气温文件时的TypeError问题

你通过OpenWeatherMap API获取罗马气温写入文件后,读取数据时触发TypeError: 'str' object is not callable,核心问题出在读取文件的代码逻辑里:

错误代码片段

rome.append(float(line()))

错误原因

line是文件读取到的字符串对象,你给它加了()试图把它当成函数调用,这就触发了类型错误。另外,每行末尾带有换行符\n,直接转float会报错,需要先清理掉空白字符。

修复后的读取代码

rome=[]
with open ('romeweather.txt','r') as f:
  for line in f:
    if len(rome) < 200:  # 用<替代<=,避免读取201条数据
      cleaned_line = line.strip()  # 去掉换行符和前后空白字符
      if cleaned_line:  # 跳过可能存在的空行
        rome.append(float(cleaned_line))

额外优化建议

  • 写入文件的效率优化:当前循环200次每次都打开关闭文件,改成一次性打开文件再循环写入,减少IO开销:
    weather= Weather()
    with open ('romeweather.txt','a') as f:
      for _ in range(200):
        f.write(weather.rome_weather())  # 函数不需要传weather参数,内部未使用该参数
    
  • 简化经纬度获取逻辑:原代码嵌套循环完全冗余,直接取API返回的第一个结果即可:
    # 替换原经纬度循环代码
    if result:
      lon = result[0]["lon"]
      lat = result[0]["lat"]
    
  • 避免变量名冲突:rome_weather函数里的参数weather和实例属性重名,且函数内部未用到该参数,直接删除该参数:
    def rome_weather(self):
        # 原有函数逻辑保持不变
    

报错信息回顾

Traceback (most recent call last):
  File "main.py", line 111, in <module>
    rome.append(float(line()))
TypeError: 'str' object is not callable

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:15:30