如何在Python中创建文件并将指定数量的随机整数写入文件

时间:2019-11-16 09:00:28

标签: python python-3.7

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语句)吗?

4 个答案:

答案 0 :(得分:3)

怎么样?

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()

答案 1 :(得分:1)

考虑一下:

from random import randint 

def main(n):
  with open('random.txt', 'w+') as file:
    for _ in range(n):
      file.write(f'{str(randint(1,5000))},')

x = int(input('How many random numbers will the file hold?: '))
main(x)

以“ w +”模式打开文件将覆盖文件中的所有先前内容,如果文件不存在,则会创建该文件。

自python 3开始,我们现在可以使用f-strings作为格式化字符串的一种巧妙方法。作为初学者,我鼓励您学习这些新奇的事物。

最后,使用with语句意味着您无需显式关闭文件。

答案 2 :(得分:0)

您可以使用名为numpy的python软件包。可以使用pip install numpy通过pip进行安装。 这是一个简单的代码

import numpy as np
arr=np.random.randint(1,5000,20)
file=open("num.txt","w")
file.write(str(arr))
file.close()

在第二行中,第三个参数20指定要生成的随机数的数量。不用硬编码,而是从用户那里获取值

答案 3 :(得分:0)

感谢大家的帮助,使用LocoGris的答案,我最终得到了这段代码,该代码可以完美回答我的问题,谢谢!我知道我需要for语句,_可以是任何正确的字母吗?

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