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

如何在Python中创建文件并向文件写入指定数量的随机整数,python,python-3.7,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')

非常熟悉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语句的次数(由用户输入)

这个怎么样

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

您可以使用名为
numpy
的python包。它可以由pip使用
pip install numpy
安装。 下面是一个简单的代码

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

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

谢谢大家的帮助,使用LocoGris的答案,我最终得到的代码完美地回答了我的问题,谢谢!我知道我需要这份声明,那可能是任何一封信对吗

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()
考虑这一点:

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+”模式打开文件将覆盖文件中以前的任何内容,如果文件不存在,它将创建该文件

从Python3开始,我们现在可以使用它作为格式化字符串的一种简洁方式。作为初学者,我鼓励你学习这些新的很酷的东西


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

是的,您将需要一个
for
循环,该循环在某个地方重复用户指定的次数。现在你只需要写一个整数。请注意,在
w
(write)模式下打开文件将擦除之前的所有内容,因此您需要考虑一下这一点,而不是回答您的问题编辑您的帖子^^
\u
可以是任何
变量
,但由于您没有使用任何
变量
<代码>\uu就像void一样,把这个计数扔掉,或者最好评论一下他的答案xD