Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取txt文件时出现索引错误_Python_Indexoutofboundsexception_Readline - Fatal编程技术网

Python 读取txt文件时出现索引错误

Python 读取txt文件时出现索引错误,python,indexoutofboundsexception,readline,Python,Indexoutofboundsexception,Readline,我是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", ci

我是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
这是我得到的索引错误:(很抱歉格式不好,仍在学习中


索引器错误回溯(最近一次调用)
在()
5当城市温度:
6.
---->7打印(标题[0]。标题(),“of”,城市温度[0],标题[2],“is”,城市温度[2],“摄氏度”)
8城市温度=平均温度readline().strip().split(','))
9
索引器:列表索引超出范围

我认为您需要检查空列表,而不是空字符串

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
实现这一点的更好(更具蟒蛇精神?)方法是:

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
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()
您可以使用file对象作为迭代器逐行读取文件。此对象不需要try块,因为循环到达空行时将正常结束。此外,请将此代码放入with语句中:

with open("myfile.txt", 'r') as mean_temp:
确保文件在读取完毕后关闭

退房:

要澄清问题中的实际情况:

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

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
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:块作为打印语句,您就完成了。太棒了!非常感谢您的帮助!我尝试过这样做,但仍然出现索引错误。Indexer-Ror回溯(最近一次调用)在()我同意你的意见,我应该检查一个空列表,但我不知道为什么我没有想到。你是检查一个空列表。如果“城市临时”为空,则它将在while循环中显示为False。对0长度的检查实际上是多余的。要真正解决索引器错误,请在问题中编辑整个错误消息,包括回溯。如果city_temp正在读取空行(strip()将在拆分发生之前删除任何空白字符),因此这里发生了其他情况。@AlanLeuthard我已附加了以前遇到的所有错误,我非常好奇为什么会发生此错误……刚刚测试过。'empty_string.split()'返回空列表。'empty_string.split(','))'返回一个包含空字符串的列表。该列表不是空的,因此city_temp为True。将'while city_temp'更改为'while city_temp[0]”以检查列表中的内容是否为空。或者使用try块。这样做了!如果没有您的帮助,我永远不会意识到这一点。再次感谢!顺便说一句,我为子孙后代添加了答案。