Skip to main content
 首页 » 编程设计

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

2025年05月04日15yjmyzz

我正在尝试创建一个写入文本文件的随机数生成器。完整代码将完美执行,但它只执行 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() 

我做了相当多的研究,但我无法弄清楚我遗漏了什么。帮忙?

请您参考如下方法:

您需要做的就是将您的 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))