python - 将循环的输出保存到文件

标签 python

我想将 for 循环的输出 (0,1,1,2,3) 保存到文件中,但我的代码只写入循环的最后一个值 (3)。我该如何修复它?

#!/usr/bin/python

def fib(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
    return a
for c in range(0, 5):
   print(fib(c))
   file=open("fib.txt","w")
   s = str(fib(c))
   file.write(s+"\n")
#   file.write("%s\n" % fib(c))
   file.close()

最佳答案

尝试一下。

def fib(n):
    a, b = 0, 1
    for i in range(0, n):
        a, b = b, a + b
    return a
file=open("fib.txt", "a")
for c in range(0, 5):
   print(fib(c))
   s = str(fib(c))
   file.write(s + "\n")
file.close()

关于python - 将循环的输出保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30370764/

相关文章:

python - Ansible playbook 在所有 Ubuntu 服务器上均失败

python - 我想在文件中的 2 个字符串之间添加一个字符串,但在输出中整个文本被 append 在文件末尾

python - Flask 和 SQLAlchemy 的 "unexpected EOF on client connection"

python - 如何使用基于numpy中日期的窗口获取时间序列的回顾移动平均值?

python正则表达式重复模式匹配

python - 无法将更大的 DataFrames 放入队列中

Python 负数的数字比较

python - 没有名为 pymindwave 的模块

python - 谷歌地球引擎 : Time series of reduceRegion()

python - 为什么 @api.doc 装饰器 python flask restplus 不更新我所做的更改?