gpt4 book ai didi

python - 如何在 Python 中按顺序向文件写入多行

转载 作者:行者123 更新时间:2023-11-28 21:57:19 26 4
gpt4 key购买 nike

请看下面的代码-

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

我做错了什么?

最佳答案

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

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

关于python - 如何在 Python 中按顺序向文件写入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19974224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com