【问题标题】:Writing a random amount of random numbers to a file and returning their squares将随机数量的随机数写入文件并返回它们的平方
【发布时间】:2012-11-03 19:34:34
【问题描述】:

所以,我正在尝试编写随机数量的随机整数(在01000 的范围内),对这些数字求平方,然后将这些平方作为列表返回。最初,我开始写入我已经创建的特定 txt 文件,但它不能正常工作。我寻找了一些我可以使用的方法,这些方法可能会使事情变得更容易一些,我发现了我认为可能有用的tempfile.NamedTemporaryFile 方法。这是我当前的代码,提供了 cmets:

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

【问题讨论】:

  • 不应该 exp = newFile(l) ** 2exp = int(l) ** 2 吗? (和 l 作为一个名字永远不会好 - line 会是一个更好的名字
  • 你为什么不使用 [random.randint(0,1000)**2 for i in range(random.randint(0,1000))] ?

标签: python math file-io python-3.x


【解决方案1】:

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

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

【讨论】:

  • 谢谢佩德罗。现在很容易理解。
【解决方案2】:

您需要在每个 int 之后放置换行符,以免它们一起运行创建一个巨大的整数:

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

(也设置模式,如 PedroRomano 的回答中所述):

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

modfile 返回一个关闭 文件句柄。您仍然可以从中获取文件名,但无法从中读取。所以在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 的参数会显示它是一个关闭的文件句柄。

测试各个部分为您提供坚实的基础,让您有条不紊地发展。

【讨论】:

  • 感谢 unutbu。请原谅我的业余语法错误。我还在学习...问题:当您返回这个临时文件时,它是否每次都会自动关闭?其余的似乎不言自明。再次,我很感激。
  • 当您说with tempfile.NamedTemporaryFile(...) as newFilewith open(...) as newFile 时,当Python 离开with 块时,文件句柄newFile自动 为您关闭。如果您不想关闭文件句柄,请使用newFile = tempfile.NamedTemporaryFile(...)。但我不建议在这里,因为您需要处理一些其他问题:(1)记得自己打电话给newFile.close()。 (2) 调用newFile.seek(0) 允许从文件的开头 读取。有关with 的更多信息,请参阅this post
猜你喜欢
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 2019-02-09
  • 2016-09-06
  • 2021-06-02
  • 2020-07-16
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多