向文本fi写入随机数生成器

2024-10-04 03:18:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个随机数生成器写入文本文件。完整的代码将完美地执行,只有一个例外,它只执行1个数字。我要12岁。我还知道,如果我使用aprint命令取出产生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()

我做了相当多的研究,但我就是搞不清我遗漏了什么。帮忙吗?在


Tags: theto代码in命令txtmainline
2条回答

您只需将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))
  1. 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) + ' ')#adds a space, unless you want the numbers to be all togerther
    
  2. 你的书面陈述应该是:

    outfile = open('numbersmake.txt', 'a+')

    所以它不会覆盖已经写过的文本,它会创建一个新的数字制造.txt“如果它不存在。

相关问题 更多 >