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

How to create a file and write a specified amount of random integers to the file in 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 语句吗?

这个怎么样?

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

第2行第三个参数20指定生成随机数的个数。取而代之的是硬编码,取值来自 user

谢谢你们的帮助,使用 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()

考虑一下:

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 语句意味着您不需要显式关闭文件。