简体   繁体   English

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

[英]Writing a random amount of random numbers to a file and returning their squares

So, I'm trying to write a random amount of random whole numbers (in the range of 0 to 1000 ), square these numbers, and return these squares as a list. 所以,我正在尝试写随机数量的随机整数(在01000的范围内),将这些数字平方,并将这些方块作为列表返回。 Initially, I started off writing to a specific txt file that I had already created, but it didn't work properly. 最初,我开始写入我已创建的特定txt文件,但它无法正常工作。 I looked for some methods I could use that might make things a little easier, and I found the tempfile.NamedTemporaryFile method that I thought might be useful. 我找了一些我可以使用的方法可能会让事情变得更容易一些,我找到了我认为可能有用的tempfile.NamedTemporaryFile方法。 Here's my current code, with comments provided: 这是我当前的代码,提供了评论:

# 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)

Unfortunately, now I'm getting this error in line 15, in my modfile function: TypeError: 'str' does not support the buffer interface . 不幸的是,现在我在第15行中遇到了这个错误,在我的modfile函数中: TypeError: 'str' does not support the buffer interface As someone who's relatively new to Python, can someone explain why I'm having this, and how I can fix it to achieve the desired result? 作为一个相对较新的Python人,有人可以解释为什么我有这个,以及如何解决它以达到预期的结果? Thanks! 谢谢!

EDIT: now fixed code (many thanks to unutbu and Pedro)! 编辑:现在修复代码(非常感谢unutbu和Pedro)! Now: how would I be able to print the original file numbers alongside their squares? 现在:我怎样才能在原来的方块旁打印原始文件号码? Additionally, is there any minimal way I could remove decimals from the outputted float? 另外,有没有什么方法可以从输出的浮点数中删除小数?

By default tempfile.NamedTemporaryFile creates a binary file ( mode='w+b' ). 默认情况下, tempfile.NamedTemporaryFile会创建一个二进制文件( mode='w+b' )。 To open the file in text mode and be able to write text strings (instead of byte strings), you need to change the temporary file creation call to not use the b in the mode parameter ( mode='w+' ): 要以文本模式打开文件并能够写入文本字符串(而不是字节字符串),您需要更改临时文件创建调用以不在mode参数中使用bmode='w+' ):

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

You need to put newlines after each int, lest they all run together creating a huge integer: 你需要在每个int之后添加换行符,以免它们一起运行创建一个巨大的整数:

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

(Also set the mode, as explained in PedroRomano's answer): (同样设置模式,如PedroRomano的回答中所述):

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

modfile returns a closed filehandle. modfile返回一个关闭的文件句柄。 You can still get a filename out of it, but you can't read from it. 您仍然可以从中获取文件名,但您无法从中读取。 So in modfile , just return the filename: 所以在modfile ,只需返回文件名:

   return newFile.name

And in the main part of your program, pass the filename on to the squared_num function: 在程序的主要部分,将文件名传递给squared_num函数:

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

Now inside squared_num you need to open the file for reading. 现在在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

Putting it all together: 把它们放在一起:

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. PS。 Don't write lots of code without running it. 不运行它就不要写很多代码。 Write little functions, and test that each works as expected. 编写小函数,并测试每个函数是否按预期工作。 For example, testing modfile would have revealed that all your random numbers were being concatenated. 例如,测试modfile会显示所有随机数都被连接在一起。 And printing the argument sent to squared_num would have shown it was a closed filehandle. 打印发送到squared_num的参数会显示它是一个封闭的文件句柄。

Testing the pieces gives you firm ground to stand on and lets you develop in an organized way. 对这些部件进行测试可以让您站稳脚跟,让您以有条理的方式进行开发。

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

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