0

I want to figure out how to print the result of my code below not in the terminal like it currently does, but change it to create a new file: output.dat and have the results printed in there. Is this possible, and if so how can I amend my code to do this? I'm a beginner btw.

from random import randint
import os

b = {}
for i in range(1000000):
    num = randint(1, 50)
    if num not in b:
        b[num] = 0
    b[num] += 1

    print ("")
for i in range(1, 51):
    print ("Number " +str(i) + ", " + str(b[i]) + "")

2 Answers2

1

Try this:

from random import randint

b = {}
for i in range(1000000):
    num = randint(1, 50)
    if num not in b:
        b[num] = 0
    b[num] += 1
with open('output.dat', 'w') as f:
    for i in range(1, 51):
        final = "Number " + str(i) + ", " + str(b[i])
        print(final)
        f.write(final + "\n")

The program will open the 'output.dat' file if its exists (if not it will create it) and write(With the 'w' mode or you can append to a file using 'a') all the information to it.

TLeo
  • 76
  • 6
0

You can modify your code this way:

from random import randint
import os

b = {}
for i in range(1000000):
    num = randint(1, 50)
    if num not in b:
        b[num] = 0
    b[num] += 1

with open('output.dat', 'w') as f:
    for i in range(1, 51):
        f.write(f'Number {i}, {b[i]}\n')
mozway
  • 194,879
  • 13
  • 39
  • 75