2017-05-10 8 views
1

ファイルを10個だけ保存しようとしています。最後のN行を保存するようにファイルに書き込む

新しいエントリを書き込むたびに、最も古いエントリが最新のものに置き換えられます。そう、私はこのファイルのappendコマンドを使用して新しい行を追加すると、それはファイルの合計行を増やすために行く

abcde-12345 
akmjk-13249 
ofdsi-
faaoj-10293 
famdk-05931 
foajq-10592 
xmdsj-19234 
boxqa-12130 
fdlsp-95392 
paidf-19341 

:そう、合計行は、ファイルの10

例常にありますファイルを追加するたびにファイルが増えます。目的は、ファイルの最初の行を削除して、行の末尾に追加することで、最も古いエントリが削除され、新しい行がファイルの総数を残して末尾に追加され、常に10に等しくなります。

私のアプローチは、これは効率的ではない、遅い、面倒という問題がある

-read the file 
-save the last 9 lines in a new file 
-add the 10th line, which is the new one 
-delete the old file, and save the new file with the same name. 

になっています。シェルスクリプトでは簡単にやり遂げることができましたが、私はPythonを使用していたので、これを行うためのより簡単な方法を望んでいました。

+0

具体的な問題の例を示すコードを教えてもらえますか?それ以外のあなたの質問を理解することは困難です。たった10行では、消費するリソースについて心配するべきではないと思います。 –

+0

call ["tail"、 " - 9"] - 最後の9行を返します – Nosyara

+0

私のケースははっきりしていないと思います。サンプルコードを追加します。 Thanks –

答えて

2

maxlen=10をバッファとして使用して、両端キューに追加します。

Juans-MBP:workspace juan$ cat 10lines.txt 
first line 
second line 
third line 
fourth line 
fith line 
sixth line 
seventh line 
eigth line 
ninth line 
tenth line 
Juans-MBP:workspace juan$ python 
Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from collections import deque 
>>> with open('10lines.txt') as f: 
...  buffer = deque(f, maxlen=10) 
... 
>>> buffer.append('first new line\n') 
>>> buffer.append('second new line\n') 
>>> with open('10lines.txt', 'w') as f: 
...  f.writelines(buffer) 
... 
>>> exit() 
Juans-MBP:workspace juan$ cat 10lines.txt 
third line 
fourth line 
fith line 
sixth line 
seventh line 
eigth line 
ninth line 
tenth line 
first new line 
second new line 
Juans-MBP:workspace juan$ 

注名前限りがf.writelinesは改行を追加しません、それを暗示する可能性があるので、あなたは、あなたは追加行がnewlinesを持っていることを確認することの世話をする必要があります。

+0

Python3は、ファイルがテキストモードで開かれている場合、 '\ n'をプラットフォームの正しい行末に自動的に変換することに言及することは重要です。 –

0

この回答をHow to delete the first line of a text file using Python?から借りて、最初の行を読み取り、削除し、新しい行を追加してファイルに書き戻します。 Python2の可能性のあるソリューションがあります。

newline = "anoth-48576" 

with open('file.txt', 'r') as fin: 
    data = fin.read().splitlines(True) 

newdata = data[1:] 

if not '\n' in newdata[-1]: 
    newdata[-1] = newdata[-1]+'\n' 

newdata.append(newline+'\n') 

with open('file.txt', 'w') as fout: 
    fout.writelines(newdata) 
関連する問題