简体   繁体   中英

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.

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.

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

hi the better way is to use logging instead to open each time file

read here: How to write to a file, using the logging Python module?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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