我在python中的列表由于某种原因被['']

时间:2020-08-07 21:12:16

标签: python list csv index-error

我有一个python程序,该程序从csv文件读取生日列表,并确定今天是否有生日。该代码应该在每一行中读取,拆分输入并将每个组件分配给适当的变量。这是代码:

# checks birthday list for any birthdays
        for entry in birthday_list:
            string = birthday_list.readline()
            string = string[:-1]
            info = string.split(',')
            print(info)
            name = info[0]
            birth_day = int(info[1])
            birth_month = int(info[2])
            birth_year = int(info[3])
            # sends message
            if (day == birth_day and month == birth_month):
                age = year - birth_year
                wish_string = 'Happy ' + str(age) + determine_ordinal(age) + ' birthday, ' + name + '!\nhttps://imgur.com/a/G3wEPyg'
                await channel.send(wish_string)
        birthday_list.close()

实际输出中包含个人信息,但这是这样的:

['Ponkachu', '7', '8', '2020']
['']

我在将birth_day分配给int(info [1])的行上收到IndexError

print(string)打印“ Ponkachu,7,8,2020”

如果我将print(info)更改为print(info [1]),它会给我“ 7”,然后是IndexError

如果我将其更改为print(len(info)),我会得到:

4

1

我绝对不知道为什么会这样。信息发生了什么?为什么突然改变了?

编辑:我刚刚检查了csv文件。 “ Ponkachu,7,8,2020”实际上是第二行,因此出于某种原因跳过了第一行。

编辑2:结果是将条目设置为第一行的输入。该代码按预期工作:

for entry in birthday_list:
            info = entry.split(',')
            info[3] = info[3][:-1]
            name = info[0]
            birth_day = int(info[1])
            birth_month = int(info[2])
            birth_year = int(info[3])
            # sends message
            if (day == birth_day and month == birth_month):
                age = year - birth_year
                wish_string = 'Happy ' + str(age) + determine_ordinal(age) + ' birthday, ' + name + '!\nhttps://imgur.com/a/G3wEPyg'
                await channel.send(wish_string)
        birthday_list.close()

2 个答案:

答案 0 :(得分:0)

迭代已经从文件中读取了一行;调用readline会得到 next 行(忽略由于迭代器的内部缓冲而导致混合迭代和readline的危险)。

    for entry in birthday_list:
        info = entry.rstrip('\n').split(',')
        print(info)
        name = info[0]
        birth_day = int(info[1])
        birth_month = int(info[2])
        birth_year = int(info[3])
        # sends message
        if day == birth_day and month == birth_month:
            age = year - birth_year
            wish_string = f'Happy {age}{determine_ordinal(age)} birthday, {name}!\nhttps://imgur.com/a/G3wEPyg'
            await channel.send(wish_string)
    birthday_list.close()

答案 1 :(得分:-1)

您的“生日清单”是文件还是普通列表?如果是文件,则在读取行本身之前不能真正使用“ for each”循环。我会去的:

list_of_lines = birthdaylist.readlines()
for each in list_of_lines:
    string = each.rstrip() //remove newline character
    rest of your code

确保使用带有S的readlines将整个文件而不是一行都显示在列表中