我正在尝试生成10个随机整数,范围从1到10,并将它们写入文件。我无法弄清楚我需要在write()函数中包含哪些参数。有什么想法吗?
import random
def main():
rand_ints = open('mynumbers.txt', 'w')
for count in range(10):
print(random.randint(0,10))
rand_ints.write( '\n')
rand_ints.close()
main()
答案 0 :(得分:1)
答案 1 :(得分:1)
首先,您不会选择任何随机数。试试random.randint(1, 10)
这段代码生成1-10的数字。
然后取出该号码int randomNumber
并将其写入文件,如下所示:
rand_ints.write(str(randomNumber) + '\n')
答案 2 :(得分:0)
import random ## imports the random module
## list comprehension, creates 10 random integers from 1 to 10 (as strings)
## and puts them in a list
x = [str(random.randint(1,10)) for i in range(10)]
myfile = open("somefile.txt", "w") ## opens your file for writing
for part in x: ## loops through your list of random numbers
myfile.write(part + "\n") ## writes them to your list along with a new line
myfile.close() ## closes your file
您的代码存在的问题是,您实际上并未使用random
生成随机数,然后您没有编写任何数字,只是将新行(\n
)写入您的文件