如何在Python中按顺序将多行写入文件

时间:2013-11-14 09:42:47

标签: python api file-io while-loop

请参阅以下代码 -

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 个答案:

答案 0 :(得分:3)

“data”仅包含分配给它的最后一个值。

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()

答案 1 :(得分: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()

答案 2 :(得分: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)

答案 3 :(得分: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)