Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将随机数生成器写入文本文件_Python_Random - Fatal编程技术网

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

Python 将随机数生成器写入文本文件,python,random,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

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

您只需将
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))
  • 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
    
  • 你的书面陈述应该是:

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

    因此,它不会覆盖已经写入的文本,如果它不存在,它将创建一个新的“numbersmake.txt”

  • 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
    
  • 你的书面陈述应该是:

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

    因此,它不会覆盖已经写入的文本,如果它不存在,它将创建一个新的“numbersmake.txt”


  • 写入语句需要位于for循环内。请修复标题。写入语句需要位于for循环内。请修复标题。