1

因此,我正在尝试编写随机数量的随机整数(在 to 范围内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)!现在:我怎样才能在它们的正方形旁边打印原始文件编号?此外,有什么最小的方法可以从输出的浮点数中删除小数吗?

4

2 回答 2

2

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

tempfile.NamedTemporaryFile(mode='w+', delete=False)
于 2012-11-03T19:53:58.133 回答
1

You need to put newlines after each int, lest they all run together creating a huge integer:

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

(Also set the mode, as explained in PedroRomano's answer):

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

modfile returns a closed filehandle. You can still get a filename out of it, but you can't read from it. So in modfile, just return the filename:

   return newFile.name

And in the main part of your program, pass the filename on to the squared_num function:

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

Now inside squared_num you need to open the file for reading.

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. 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. And printing the argument sent to squared_num would have shown it was a closed filehandle.

Testing the pieces gives you firm ground to stand on and lets you develop in an organized way.

于 2012-11-03T20:07:36.307 回答