0

私は小さなクラスを作成して、python の上に暗号化の層を追加しましたtempfile.TemporaryFIle。への最初の呼び出しreadlineは (予想どおり) 行を返しますが、その関数への後続の呼び出しはすべて空の文字列を返します。

ソースコードを表示する前に、上記の動作の例を次に示します。

lines = ["Now is the winter of our discontent",
        "Made glorious summer by this sun of York;",
        "And all the clouds that lour'd upon our house",
        "In the deep bosom of the ociean buried."]

f = EphemeralFile()
f.write('\n'.join(lines))  # just in case writelines is screwing up as well

f.readline()
f.readline()

出力:

'Now is the winter of our discontent'
''

そして、ここにコメント付きのクラス メソッドがあります。このメソッドが属するクラスはのサブクラスではないFileことに注意してください。代わりに、 への参照を保持し、のtell メソッドtempfile.TemporaryFileなどのメソッドをエイリアスします。self.tellTemporaryFile

def readline(self, size=-1):
    fptr = self.tell()  # alias of self._file.tell
    bytes = []
    got_line = False
    while not got_line:
        # self.read is NOT an alias, but calls self._file.read
        bytes.append(self.read(256))  
        offset = '\n' in bytes[-1]
        if not bytes[-1] or offset:
            end = bytes.pop().split('\n', 1)[0]
            bytes.append(end)
            got_line = True

    plaintext = ''.join(bytes)
    # seek is aliased from self._file.seek
    self.seek(fptr + len(plaintext) + offset)  # rewind; offset is bool.
    return plaintext

私は一生、どこで間違ったのかを理解することはできません。これは私のばかげた見落としであるというしつこい疑いがあるので、新鮮な目で見ていただければ幸いです。

前もって感謝します!

編集:興味のある方は、クラス全体をご覧ください。

4

1 に答える 1

0

考えられる説明: Windows を使用しており、ファイルをテキスト モードで開いています。行は で終わります\r\nが、\r文字は削除されます。次に、次の行を探していると思うと、実際には\n.

ちなみに、呼び出し元が空行とファイルの終わりを区別できるように、 の戻り値にreadline()は が含まれている必要があります。\n

于 2013-05-16T13:08:02.747 に答える