简体   繁体   English

如何将for循环中的每个打印逐行存储到文件中?

[英]How to store every print in the for loop to a file line by line?

Okay, So I´m doing a program that simulates dice rolls and then saves them to a file.好的,所以我正在做一个模拟掷骰子的程序,然后将它们保存到一个文件中。 I thought that the easiest option, in my opinion, would be to just save every single iteration of the loop and save the print to the file line by line.我认为,在我看来,最简单的选择就是保存循环的每一次迭代,并将打印内容逐行保存到文件中。 But unfortunately, I cannot figure it out.但不幸的是,我无法弄清楚。

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

Secondly, I thought I could save all the variables to the list and then somehow through some function save it to a file.其次,我认为我可以将所有变量保存到列表中,然后以某种方式通过一些 function 将其保存到文件中。

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

There I added all the data to the list.在那里,我将所有数据添加到列表中。

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

I added it to the file here.我在这里将它添加到文件中。 My output in the file is this: "115216314412511" I don't know how I should do it so that all 3 numbers are would be together in one line like in the code.我在文件中的 output 是这样的:“115216314412511”我不知道我应该怎么做才能让所有 3 个数字像代码中一样在一行中。

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

Append a Carriage Return "/r" with in the for loop after the append throw Append 在 append 抛出后的 for 循环中带有回车符“/r”

hi the better way is to use logging instead to open each time file嗨,更好的方法是使用logging来打开每个时间文件

read here: How to write to a file, using the logging Python module?在这里阅读: 如何使用日志记录 Python 模块写入文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM