python - 如何在 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()
推荐阅读
- html - 如何用三角形制作透明泡泡聊天?
- jms - REST POST 与 POSTMAN 一起正常工作,但在使用 Spring RestTemplate 从客户端调用时出现异常
- c - Malloc 在某些调用后无法工作(C,在 Windows 10 上使用 gcc 为 MinGW-W64 编译)
- node.js - 为什么回调discord.js时数组不会从此函数传递
- javascript - 如何从 vue js 模板中将参数传递给方法调用?
- java - 如何以非常小的加速度和速度为运动物体设置动画?
- oracle - ORA-01008: 并非所有变量都绑定错误并且无法识别未绑定变量
- go - 如何覆盖文件但跳过一个特定的文件名
- ios - 您可以将传入的电话号码存储为 iO 上的变量吗?
- elasticsearch - Stormcrawler: indexer.md.mapping - 如果元数据标签不存在会发生什么?