【问题标题】:Index error when reading txt file读取txt文件时出现索引错误
【发布时间】:2017-06-22 15:25:16
【问题描述】:

我是 python 新手,使用 Jupityr 笔记本在 edx 上做一些基本的编码作业。我在一项我无法弄清楚的作业中遇到了索引错误。作业让我在 while 循环中一次读取一行文本文件,并以特定格式打印输出。我的代码如下

city_temp = mean_temp.readline().strip().split(',')

while city_temp:

    print (headings[0].title(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
    city_temp = mean_temp.readline().strip().split(',')

代码运行整个文件,但不是在空行结束“while”循环,而是继续运行并创建一个空列表。我不确定为什么会发生这种情况,也无法自己解决。我尝试为空字符串添加“if”测试并中断,并且还编写了额外的空文本行,但没有一个选项导致任何成功。如果有人有想法,我将不胜感激!

我也有一个 txt 文件包含的内容的摘录粘贴在下面。还有其他城市,但我认为没有必要将每个城市都包括在内:

city,country,month ave: highest high,month ave: lowest low
Beijing,China,30.9,-8.4

这是我得到的索引错误:(抱歉格式不好,仍在学习


IndexError                                Traceback (most recent call last)
<ipython-input-18-6ea7e8e263b5> in <module>()
      5 while city_temp:
      6 
----> 7     print (headings[0].title(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
      8     city_temp = mean_temp.readline().strip().split(',')
      9 

IndexError: list index out of range

【问题讨论】:

  • 要真正解决您的 IndexError,请将您的整个错误消息(包括回溯)编辑到您的问题中。如果 city_temp 正在读取一个空行,它应该是一个空列表(strip() 会在拆分发生之前删除任何空白字符),所以这里还有其他事情发生。
  • @AlanLeuthard 我已经附上了我之前遇到的整个错误,我很好奇为什么会发生这个错误
  • 啊啊啊……刚刚测试过了。 'empty_string.split()' 返回一个空列表。 'empty_string.split(',')' 返回一个包含空字符串的列表。该列表不为空,因此 city_temp 为 True。将 'while city_temp' 更改为 'while city_temp[0]' 以检查列表中的内容是否为空。或者使用 try 块。
  • 做到了!如果没有你的帮助,我永远不会意识到这一点。再次感谢!
  • 我添加到答案顺便说一句,为了后代。

标签: python indexoutofboundsexception readline


【解决方案1】:

实现此目的的更好(更pythonic?)方法是:

for line in mean_temp:
    city_temp = line.strip().split(',')
    try:
        print ("{} of {} {} is {} Celsius".format(headings[0].title(),
                                                  city_temp[0], 
                                                  headings[2],
                                                  city_temp[2]))
    except IndexError:
        break

您可以使用文件对象作为迭代器逐行读取文件。这个不应该需要 try 块,因为循环会在到达空行时优雅地结束。另外,将此代码放在 with 语句中:

with open("myfile.txt", 'r') as mean_temp:

确保文件在您完成阅读后关闭。

查看:https://docs.python.org/3/tutorial/inputoutput.html

澄清问题的实际情况:

当 readline() 到达文件末尾时,它返回一个空字符串。当您对空字符串使用 strip() 时,它会返回一个空列表。当您在空字符串上使用 strip(',') 或任何分隔符时,它会返回一个包含空字符串的列表。在这种情况下,您的 while 循环正在检查列表。由于列表不是空的,它返回 True 并且 while 循环继续。如果您需要 while 循环,我的建议是:

line = mean_temp.readline()
while line:
    city_temp = line.strip().split(',')
    print ("{} of {} {} is {} Celsius".format(headings[0].title(),
                                              city_temp[0], 
                                              headings[2],
                                              city_temp[2]))
    line = mean_temp.readline()

这可能是 while 循环遍历文件的最简洁方式。与上面的 for 循环几乎完全一样。

【讨论】:

  • 这是个好主意,感谢您的提示!不幸的是,我所做的提交需要存在 while 循环,但我将来肯定会使用 try 命令。
  • 然后保持readline()初始条件和while循环。为您的打印语句使用 try: 块,您就完成了。
  • 太棒了!非常感谢您的帮助!
【解决方案2】:

我相信你需要检查空列表而不是空字符串

city_temp = mean_temp.readline().strip().split(',')

while city_temp:

   print (headings[0].title(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
   city_temp = mean_temp.readline().strip().split(',')
   if len(city_temp) == 0:
     break

【讨论】:

  • 我试过这样做,但我仍然得到索引错误。 IndexError Traceback (最近一次调用最后一次) in () 我同意你的评论,我应该检查一个空列表,但我不知道为什么我没有想想吧。
  • 您正在检查一个空列表。如果“city_temp”为空,那么它将在 while 循环中显示为 False。检查 0 长度实际上是多余的。
猜你喜欢
  • 2019-06-08
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多