1

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

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

各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出力すると、それが閉じたファイルハンドルであることが示されます。

ピースをテストすることで、立ち上がるための確固たる基盤が得られ、組織化された方法で開発することができます。

于 2012-11-03T20:07:36.307 に答える