请看下面的代码——
from sys import argv
from urllib2 import urlopen
from os.path import exists
script, to_file = argv
url = "http://numbersapi.com/random"
fact = 0
number = 0
print "Top 5 Facts of The World"
while fact < 5:
response = urlopen(url)
data = response.read()
fact += 1
number += 1
print
print "%s). %s " % (str(number), data)
print "Now, let us save the facts to a file for future use."
print "Does the output file exist? %r" % exists(to_file)
print "When you are ready, simply hit ENTER"
raw_input()
out_file = open(to_file, 'w')
out_file.write(data)
print "Alright, facts are saved in the repo."
out_file.close()
上面代码中的问题是当我打开 file1.txt 时,我只看到打印了 1 个事实。作为一种变体,我将所有内容都带入了 while 循环。它会导致同样的问题。我相信它写了一个事实,然后用下一个和下一个覆盖,直到只保存最后一个事实。
我究竟做错了什么?