gpt4 book ai didi

python - 将随机数量的随机数写入文件并返回它们的平方

转载 作者:行者123 更新时间:2023-11-30 23:39:48 25 4
gpt4 key购买 nike

因此,我尝试编写随机数量的随机整数(在 01000 范围内),对这些数字进行平方,然后返回这些平方作为一个列表。最初,我开始写入已创建的特定 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)

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

编辑:现在修复了代码(非常感谢unutbu和Pedro)!现在:我如何才能在其方 block 旁边打印原始文件编号?另外,有没有什么最小的方法可以从输出的 float 中删除小数?

最佳答案

默认 tempfile.NamedTemporaryFile 创建一个二进制文件( mode='w+b' )。要以文本模式打开文件并能够写入文本字符串(而不是字节字符串),您需要更改临时文件创建调用以不使用 bmode参数(mode='w+'):

tempfile.NamedTemporaryFile(mode='w+', delete=False)

关于python - 将随机数量的随机数写入文件并返回它们的平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com