1

ウェブサイトからデータを取得してテキスト ファイルに記録する Python プログラムの作成に取り組んでいます。これで最後の 1000 個のエントリ (4 個と文字列 "hello" でテスト中) を記録し、残りを削除します。これが私がこれまでに持っているものです:

f = open("test.txt", "r")
text = f.read()

f = open("test.txt", "w")
content = text.splitlines(True)
f.write("hello")
f.write("\n")

for x in range(0,4):
    f.write(str(content[x:x+1]).strip('[]'))

f.close()

ただし、これは「機能します」が、テキストファイルを次のようにフォーマットします。

hello
'hello\n''\'hello\\n\'\'\\\'hello\\\\n\\\'\\\'\\\\\\\'hello\\\\\\\\n\\\\\\\'"\\\\\\\'hello\\\\\\\\\\\\\\\\n\\\\\\\'"\\\'\''

これを理解するのを手伝ってもらえますか。次のようになります。

hello
hello
hello
hello

ありがとうございました!

4

1 に答える 1

0

maxlen を提供する deque を使用します。行/単語を追加すると、maxlen 個の項目のみが保持され、新しい項目が追加され、古い項目は忘れられます。

from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
with open(fname) as f:
  text = f.read()
  for line in text.splitlines(True):
    last_lines.append(line)
#f is closed when we leave the block 

outfname = fname
with open(outfname, "w") as of:
  for line in last_lines:
    of.write(line)

分割線がなくても実行できます(ただし、要求されました)。

from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
for line in open(fname):
  last_lines.append(line)
#file is closed when we leave the (for) block

outfname = fname
with open(outfname, "w") as of:
  for line in last_lines:
    of.write(line)

また、Jon Clements のトリック (ファイル記述子から作成された反復子を使用して両端キューを作成する) を使用し、別のソース ファイルとターゲット ファイルを使用できるようにすると、非常に短くなります。

from collections import deque
with open("target.txt", "w") as out_f:
  for line in deque(open("source.txt"), maxlen = 4):
    out_f.write(line)
于 2013-10-09T23:24:34.887 に答える