だから、私はランダムな量のランダムな整数(からの範囲)を書き、これらの数を二乗し、これらの二乗をリストとして返すことを試みて0
い1000
ます。最初は、すでに作成した特定の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に感謝します)!さて、元のファイル番号を正方形と一緒に印刷するにはどうすればよいですか?さらに、出力されたフロートから小数を削除するための最小限の方法はありますか?