python如何将生成的随机数存入文件中_将随机数写入文件并返回它们的平方

所以,我试图写一个随机的整数(在0到1000)的范围内,将这些数字平方,并以列表的形式返回这些平方。最初,我开始写我已经创建的一个特定的txt文件,但它不能正常工作。我寻找了一些可以让事情变得简单一点的方法,我发现了我认为可能有用的tempfile.NamedTemporaryFile方法。以下是我当前的代码,并提供了注释:# This program calculates the squares of numbers read from a file, using several functions

# reads file- or writes a random number of whole numbers to a file -looping through numbers

# and returns a calculation from (x * x) or (x**2);

# the results are stored in a list and returned.

# Update 1: after errors and logic problems, found Python method tempfile.NamedTemporaryFile:

# This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system, and creates a temprary file that can be written on and accessed

# (say, for generating a file with a list of integers that is random every time).

import random, tempfile

# Writes to a temporary file for a length of random (file_len is >= 1 but <= 100), with random numbers in the range of 0 - 1000.

def modfile(file_len):

with tempfile.NamedTemporaryFile(delete = False) as newFile:

for x in range(file_len):

newFile.write(str(random.randint(0, 1000)))

print(newFile)

return newFile

# Squares random numbers in the file and returns them as a list.

def squared_num(newFile):

output_box = list()

for l in newFile:

exp = newFile(l) ** 2

output_box[l] = exp

print(output_box)

return output_box

print("This program reads a file with numbers in it - i.e. prints numbers into a blank file - and returns their conservative squares.")

file_len = random.randint(1, 100)

newFile = modfile(file_len)

output = squared_num(file_name)

print("The squared numbers are:")

print(output)

不幸的是,现在我在第15行的modfile函数中得到了这个错误:TypeError: 'str' does not support the buffer interface。作为一个对Python比较陌生的人,有人能解释一下我为什么要这样做,以及我如何修复它以达到预期的结果吗?谢谢!在

编辑:现在修复了代码(多亏了unutbu和Pedro)!现在:我怎样才能把原始文件编号打印在它们的方块旁边呢?另外,有没有什么方法可以从输出的浮点中去掉小数?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值