How to save a result in txt

Asked

Viewed 2,558 times

1

I have this code that generates combinations of numbers. When I run it, these combinations are printed on the screen.
What I want is for it to save these combinations in a txt file.

import random

c1 = (random.choice([9, 9]))
c2 = (random.choice([1, 1]))
c3 = (random.choice([9, 9, 9]))

def gerar_randomico():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9])

def gerar_randomicus():
    return random.choice([6, 7, 8, 9])

for i in range(3):
    print ('{}{}{}{}{}{}{}{}{}{}{}'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(),gerar_randomico(), gerar_randomico(),gerar_randomico(),gerar_randomico(),gerar_randomico(), gerar_randomico()))
  • 1

    just take and save the numbers in a list, giving an append, and then create a txt file and make it write.

1 answer

2

just take and save the numbers in a list, giving an append, and then create a txt file and make it write.

What I did was create an empty list at the beginning, and in your for, instead of printing, I kept the number in a list, and then I created the file.

import random

c1 = (random.choice([9, 9]))
c2 = (random.choice([1, 1]))
c3 = (random.choice([9, 9, 9]))
lista = []

def gerar_randomico():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9])

def gerar_randomicus():
    return random.choice([6, 7, 8, 9])

for i in range(3):
    lista1 = ('{}{}{}{}{}{}{}{}{}{}{}'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(),gerar_randomico(), gerar_randomico(),gerar_randomico(),gerar_randomico(),gerar_randomico(), gerar_randomico()))
    with open('arquivo.txt','a') as arquivo:
        arquivo.write(str(lista1))
        lista_guardar = lista.append(arquivo)
        print(lista_guardar)
  • 4

    I don’t think you want to open the same file with the option w: https://docs.python.org/3/library/functions.html#open ... how about opening with a?

  • 1

    truth, my mistake, I already packed in the code, thanks for the touch.

  • I am extremely beginner, I don’t know if I expressed myself well but what I wanted is to save the result in a.txt file, for this txt file appear for example on the desktop of my pc, I tried this code that you edited for me, but it’s not what I got, If it’s not too much abuse I’d like one more help and I thank you for that.

  • actually I found yes the txt file with the result, but the problem now was another kkkk, inside the txt the results are next to each other, I could not make stay one below the other, generated 3 combinations but is next to each other instead of one on top of the other.

  • But why can’t it be like that ? When you pull from the text file you just give a split(',') that it will cut right into the commas and you will give the text clean.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.