我正在尝试创建一个随机数生成器写入文本文件。完整的代码将完美地执行,只有一个例外,它只执行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()
我做了相当多的研究,但我就是搞不清我遗漏了什么。帮忙吗?在
您只需将
write()
语句放入for
循环中。在write语句必须在for循环中:
你的书面陈述应该是:
outfile = open('numbersmake.txt', 'a+')
所以它不会覆盖已经写过的文本,它会创建一个新的数字制造.txt“如果它不存在。
相关问题 更多 >
编程相关推荐