首页 > 解决方案 > 如何在 Python 中创建文件并将指定数量的随机整数写入文件

问题描述

对 Python 和编程非常陌生。问题是创建一个将一系列随机数写入文本文件的程序。每个随机数应该在 1 到 5000 的范围内。应用程序允许用户指定文件将保存多少个随机数。到目前为止,我的代码如下:

 from random import randint
 import os
 def main ():
     x = int(input('How many random numbers will the fille hold?: '))
     temp_file = open('temp.txt', 'w')
     temp_file.write(str(randint(1,5000)))
  main()

我在实现将随机整数 1-5000 写入文件 x 次(由用户输入)的逻辑时遇到问题 我会使用 for 语句吗?

标签: pythonpython-3.7

解决方案


这个怎么样?

from random import randint
import os
def main ():
     x = int(input('How many random numbers will the fille hold?: '))
     temp_file = open('temp.txt', 'w')
     for _ in range(x):
         temp_file.write(str(randint(1,5000))+" ")
     temp_file.close() 
main()

推荐阅读