将随机数生成器写入文本文件
Writing a random number generator to a text file
我正在尝试创建一个写入文本文件的随机数生成器。完整代码将完美执行,但它只执行 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))
您的写入语句需要在您的 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'。
我正在尝试创建一个写入文本文件的随机数生成器。完整代码将完美执行,但它只执行 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))
您的写入语句需要在您的 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'。