将随机数的随机数写入文件并返回其正方形



因此,我正在尝试编写随机数量的随机数量(在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)

不幸的是,现在我在第15行中遇到了此错误:modfile函数:TypeError: 'str' does not support the buffer interface。作为一个对Python相对较新的人,有人可以解释为什么我要有这个,以及如何解决它以实现所需的结果?谢谢!

编辑:现在修复了代码(非常感谢UNUTBU和PEDRO)!现在:我如何能够与它们的正方形一起打印原始文件编号?另外,我可以从输出的浮点上删除小数的最小方法吗?

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

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

您需要在每次int之后放置新线,以免它们一起创建一个巨大的整数:

newFile.write(str(random.randint(0, 1000))+'n')

(也设置模式,如Pedroromano的答案中所述):

   with tempfile.NamedTemporaryFile(mode = 'w+', delete = False) as newFile:

modfile返回封闭 filehandle。您仍然可以从中获取文件名,但是您无法从中读取。因此,在modfile中,只需返回文件名:

   return newFile.name

,在程序的主要部分中,将文件名传递到squared_num函数:

filename = modfile(file_len)
output = squared_num(filename)

现在在squared_num内您需要打开文件以进行阅读。

with open(filename, 'r') as f:
    for l in f:
        exp = float(l)**2       # `l` is a string. Convert to float before squaring
        output_box.append(exp)  # build output_box with append

将它们放在一起:

import random, tempfile 
def modfile(file_len):
       with tempfile.NamedTemporaryFile(mode = 'w+', delete = False) as newFile:
            for x in range(file_len):
                 newFile.write(str(random.randint(0, 1000))+'n')
            print(newFile)
       return newFile.name
# Squares random numbers in the file and returns them as a list.
def squared_num(filename):
    output_box = list()
    with open(filename, 'r') as f:
        for l in f:
            exp = float(l)**2
            output_box.append(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)
filename = modfile(file_len)
output = squared_num(filename)
print("The squared numbers are:")
print(output)

ps。不要在不运行的情况下编写很多代码。写很少的功能,并测试每个功能是否按预期工作。例如,测试modfile会揭示您的所有随机数都被串联。并打印发送给squared_num的参数表明它是一个封闭的filehandle。

测试这些零件可以使您坚定地站立并让您以有组织的方式发展。

最新更新