Python 将随机数生成器写入文本文件
我正在尝试创建一个随机数生成器来写入文本文件。完整代码将完美执行,但只执行1个数字。我需要它是12。我还知道,如果我使用ap-rint命令取出生成12个数字的代码,但一旦我在没有print命令的情况下将其插入并尝试将其发送到txt文件,它就会返回到只执行1Python 将随机数生成器写入文本文件,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
#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))
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 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循环内。请修复标题。