簡體   English   中英

將隨機數量的隨機數寫入文件並返回其正方形

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

所以,我正在嘗試寫隨機數量的隨機整數(在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參數中使用bmode='w+' ):

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返回一個關閉的文件句柄。 您仍然可以從中獲取文件名,但您無法從中讀取。 所以在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的參數會顯示它是一個封閉的文件句柄。

對這些部件進行測試可以讓您站穩腳跟,讓您以有條理的方式進行開發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM