2

请看下面的代码——

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 循环。它会导致同样的问题。我相信它写了一个事实,然后用下一个和下一个覆盖,直到只保存最后一个事实。

我究竟做错了什么?

4

4 回答 4

3

“数据”仅保存分配给它的最后一个值。

from sys import argv

script, to_file = argv

fact = 0
number = 0

out_file = open(to_file, 'w')
while fact < 5:
    data = str(fact)
    out_file.write(str(data) + '\n')
    fact += 1
    number += 1
    print
    print "%s). %s " % (str(number), data)
out_file.close()
于 2013-11-14T09:52:11.437 回答
2

data每次循环迭代都会覆盖。尝试这个:

out_file = open(to_file, 'w')
while fact < 5:
    response = urlopen(url)
    data = response.read()
    fact += 1
    number += 1
    print
    print "%s). %s " % (str(number), data)
    out_file.write(data)
    out_file.write('\n') #one fact per line

out_file.close()
于 2013-11-14T09:46:12.560 回答
0

看来您正在覆盖循环中的数据,所以最后您只有最后一个数据。尝试更改为这样的:

[...]
final_data=''
while fact < 5:
    response = urlopen(url)
    data = response.read()
    fact += 1
    number += 1
    print
    print "%s). %s " % (str(number), data)
    final_data+=data

[...]
out_file.write(final_data)
于 2013-11-14T09:47:27.050 回答
0

问题是您在循环之后写入文件,因此data指向最后获取的 url 数据。要解决此问题,请将其存储data在列表中,然后将列表中的所有内容写入如下:

for fact in data:
    out_file.write(fact + '\n')

您需要像这样附加获取的事实:

data.append(response.read())

或者在获取事实之前询问您是否要将其写入文件,然后像这样移动文件操作:

with open(to_file, 'wb') as out_file:
    while fact < 5:
        response = urlopen(url)
        data = response.read()
        if should_write:
            out_file.write(data + '\n')
        fact += 1
        number += 1
        print
        print "%s). %s " % (str(number), data)
于 2013-11-14T09:49:29.577 回答