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

AttributeError排查:列表对象无strip属性 代码运行报错求助

问题分析与解决:AttributeError: 'list' object has no attribute 'strip'

错误原因

使用csv.reader读取CSV文件时,循环迭代得到的line是列表类型(对应CSV一行中的各列值),而strip()是字符串专属方法,列表没有这个属性,直接调用就会触发报错。

修正方案

csv.reader已经自动将每行数据按分隔符分割成列表,无需再手动调用strip()和split()处理,直接按索引取对应列值即可。如果CSV文件首行是表头,记得先跳过表头行。

修正后的代码

from Country import Country
import csv


class CountryIRSystem:
    def __init__(self):
        self.__list_countries = []

    def search_name(self, country_name):
        for country in self.__list_countries:
            if country.country_name == country_name:
                return country_name
        return None

    def create_info(self, country_data):
        with open(country_data, "r") as csvfile:
            csvreader = csv.reader(csvfile)
            # 若CSV首行是表头,执行此语句跳过(根据实际情况决定是否保留)
            next(csvreader)
            for line in csvreader:
                country = Country()
                # 直接从列表line中按索引取对应列的值
                country.country_name = line[2]
                country.country_code = line[3]
                country.acc_to_clean_fuel = line[4]
                country.acc_to_elec = line[5]
                country.annual_freshwater_withdrawl = line[6]
                country.armed_forces_tot = line[7]
                country.expense_gdp = line[8]

                self.__list_countries.append(country)

额外提示

  • 确认CSV文件的列顺序和你使用的索引完全匹配,避免出现IndexError索引越界错误。
  • 如果CSV的分隔符不是默认逗号,可以在初始化csv.reader时指定delimiter参数,比如csv.reader(csvfile, delimiter='\t')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:33:11