为什么不打破?

时间:2018-06-11 23:24:38

标签: python

我写了一些我必须提交给在线编程课程的代码。该代码旨在:

  • 导入并打开文件
  • 将数据附加到所述文件
  • 从上述文件中读取,以摄氏度显示每个城市名称和月平均高温。

输出应该如下所示:

City of Beijing month ave: highest high is 30.9 Celsius  
City of Cairo month ave: highest high is 34.7 Celsius  
City of London month ave: highest high is 23.5 Celsius  
City of Nairobi month ave: highest high is 26.3 Celsius  
City of New York City month ave: highest high is 28.9 Celsius  
City of Sydney month ave: highest high is 26.5 Celsius  
City of Tokyo month ave: highest high is 30.8 Celsius  
City of Rio De Janeiro month ave: highest high is 30.0 Celsius  

当代码运行时,它进入无限循环,我不明白为什么。我认为当文件指针到达文件的末尾时,代码会中断,因为读取将等于“”(空字符串)并且它是Falsey所以它会停止。

我知道编写没有关键字“while”的代码会更好,但在我的类中,关键字必须在代码中。我让代码与for / in关键字完美配合。

非常感谢任何帮助。

代码:

!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp_file = open("mean_temp.txt","a+")
mean_temp_file.write("Rio de Janeiro,Brazil,30.0,18.0\n")


mean_temp_file.seek(0)

headings = mean_temp_file.readline()

headings_list = headings.split(",")

city_temp = mean_temp_file.readlines()

while city_temp: 
    for each_line in city_temp:
        each_line_list = each_line.split(",")
        print(headings_list[0].title(),"of",each_line_list[0].title(),headings_list[2],"is",each_line_list[2],"Celsius.")

mean_temp_file.close()

如果它有帮助,我在Microsoft Azure笔记本中编写了代码。

1 个答案:

答案 0 :(得分:2)

您已创建city_temp作为文件中所有行(但第一行)的列表:

city_temp = mean_temp_file.readlines()

您永远不会在循环内的任何位置修改该列表。因此,如果第一次它是非空的(因此是真实的),那么它将永远是非空的。

目前尚不清楚你真正想要用这个循环做什么。您已经有一个遍历文件中每一行的内部循环:

for each_line in city_temp:

......这似乎是你需要的唯一循环。所以,只需摆脱外部while循环。:

city_temp = mean_temp_file.readlines()

for each_line in city_temp:
    each_line_list = each_line.split(",")
    print(headings_list[0].title(),"of",each_line_list[0].title(),headings_list[2],"is",each_line_list[2],"Celsius.")

虽然我们在这里,但您不需要readlines()。这会将所有剩余的行读入一个列表,这样你就可以遍历它 - 但是文件本身就是同一行的迭代器,所以你也可以循环遍历它,而不会浪费时间,内存和一行代码列表:

for each_line in mean_temp_file:
    each_line_list = each_line.split(",")
    print(headings_list[0].title(),"of",each_line_list[0].title(),headings_list[2],"is",each_line_list[2],"Celsius.")

最后,使用csv模块可能会更容易:

import csv
mean_temp_file = open("mean_temp.txt","a+")
mean_temp_file.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp_file.seek(0)
for row in csv.DictReader(mean_temp_file):
    # here row is a dict, where the keys are the header names, 
    # and the values are this row's values