【问题标题】:How to store every print in the for loop to a file line by line?如何将for循环中的每个打印逐行存储到文件中?
【发布时间】:2020-08-09 21:50:46
【问题描述】:

好的,所以我正在做一个模拟掷骰子的程序,然后将它们保存到一个文件中。 我认为,在我看来,最简单的选择就是保存循环的每一次迭代并将打印逐行保存到文件中。但不幸的是,我无法弄清楚。

import random
output=[]
order=0
inpu_t=int(input("Enter the number of simulated throws: "))
f = open('file.txt','w')
figures = (0,)*6

for i in range(inpu_t):
    order = order+1
    throw = random.randint(1, 6)
    figure = figures[throw -1]+1
    print(order,'.throw  and {}-times fell the number {}.'.format(figure, throw ))
    output.append(order)
    output.append(figure)
    output.append(throw )
    figures = figures[:throw -1]+(figure,)+figures[throw :]

print("\n")
with open('file.txt', 'w') as f:
    for item in output:
        f.write("%s" % item)
for i in range(6):
    print('The number {} fell {}-times.'.format(i+1, figures[i]))

其次,我认为我可以将所有变量保存到列表中,然后以某种方式通过某些函数将其保存到文件中。

output.append(order)
output.append(figure)
output.append(throw )

我将所有数据添加到列表中。

with open('file.txt', 'w') as f:
    for item in output:
        f.write("%s" % item)

我在此处将其添加到文件中。 我在文件中的输出是这样的:“115216314412511” 我不知道我应该怎么做才能让所有 3 个数字像代码一样在一行中。

print(order,'.throw  and {}-times fell the number {}.'.format(figure, throw ))

【问题讨论】:

    标签: python printing


    【解决方案1】:

    在追加抛出后的for循环中追加一个回车符“/r”

    【讨论】:

      【解决方案2】:

      你好,更好的方法是使用logging而不是打开每个时间文件

      在这里阅读:How to write to a file, using the logging Python module?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        相关资源
        最近更新 更多