我有一个excel文档,里面填写了我想要打印出我的python代码的信息。为了让大家知道我的excel文档是什么样的,我将打印出一些代码:
import csv
file = csv.reader(open("n:\population.csv"))
print file.next()
这给了我们以下输出:
['country', 'country isocode', 'year', 'POP']
但这不是我要打印的部分,相关信息在其他行,所以如果我再输入一个 file.next()我们得到以下信息:< / p>
['Netherlands', 'NLD', '1950', '10113.527']
如果我需要的相关信息,现在我只需要打印年份和人口(POP),并为我的文档中的每一行执行此操作。所以我想出了以下代码来做到这一点:
import csv
file = csv.reader(open("population.csv"))
print file.next()
def print_population_list(filename):
population_list_length = len("population.csv")
number = 0
line = file.next()
while number < population_list_length:
print line[2:]
population_list_length = population_list_length - 1
print_population_list('N:\population.csv')
问题是这段代码的输出如下:
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
那么我如何让我的代码打印出我的文档的下一行,而不是一遍又一遍地打印相同的行,直到数字&gt; population_list_length。
如果有人可以帮我解决这个问题,我会非常感激
答案 0 :(得分:0)
马上,你没有做过的事情就是在while循环中前进(或者在for循环中)。
您已将行定义为file.next(),但告诉它一遍又一遍地从同一行打印部件。
尝试此操作,在您打印完数据后,请注意在每个循环结束时前进行:
def print_population_list(filename):
population_list_length = len("population.csv")
number = 0
line = file.next()
while number < population_list_length:
print line[2:]
# the next line of code advances the line in the file
line = file.next()
population_list_length = population_list_length - 1
# you don't need to advance the line here,
# as you've already advanced it at the end of the last loop
for contry, isocode, year, population in
print line[2:]
# the next line of code advances the line in the file
line = file.next()
population_list_length = population_list_length - 1