繁体   English   中英

如何在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()

我在实现将随机 integer 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()

考虑一下:

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

您可以使用名为 numpy 的 python numpy 它可以通过 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()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM