将随机数生成器写入文本文件

Car*_*ugh 1 python random

我试图创建一个写入文本文件的随机数生成器.完整代码将完美执行,除了它只执行1个数字.我需要它为12.我也知道如果我使用ap rint命令取出产生12个数字的代码,但是一旦我将其插入而没有print命令并尝试将其发送到txt文件它回到只做1.

#This program writes 1 line of 12 random integers, each in the
#range from 1-100 to a text file.

def main():

    import random

    #Open a file named numbersmake.txt.
    outfile = open('numbersmake.txt', 'w')

    #Produce the numbers
    for count in range(12):
        #Get a random number.
        num = random.randint(1, 100)

    #Write 12 random intergers in the range of 1-100 on one line
    #to the file.
    outfile.write(str(num))

    #Close the file.
    outfile.close()
    print('Data written to numbersmake.txt')

#Call the main function
main()
Run Code Online (Sandbox Code Playgroud)

我做了很多研究,但我不知道我错过了什么.救命?

Chr*_*son 6

您需要做的就是将write()语句放在for循环中.

for count in range(12):
    #Get a random number.
    num = random.randint(1, 100)
    #Write 12 random intergers in the range of 1-100 on one line
    #to the file.
    outfile.write(str(num))
Run Code Online (Sandbox Code Playgroud)