2016-04-22 9 views
6

私は、.txtファイルから特定の行を書き換えるコードを作ろうとしています。 私が望む行に書き込むことができますが、行の前のテキストを消去することはできません。ここでPythonのテキストファイルから行を消す方法は?

は私のコードです:
(私は物事のカップルをしようとしている)

def writeline(file,n_line, text): 
    f=open(file,'r+') 
    count=0 
    for line in f: 
     count=count+1 
     if count==n_line : 
      f.write(line.replace(str(line),text)) 
      #f.write('\r'+text) 

あなたがテストのためのテストファイルにするには、このコードを使用することができます:

with open('writetest.txt','w') as f: 
    f.write('1 \n2 \n3 \n4 \n5') 

writeline('writetest.txt',4,'This is the fourth line') 

編集を:何らかの理由で、 'if count == 5:'を使用すると、コードはokをコンパイルします(前のテキストを消去しなくても)。しかし、if count == n_line: 'ならば、ファイルはごみがたくさん。

回答はうまくいきますが、私のコードで何が問題になっているのか、読み書きできない理由を知りたいと思います。ありがとう!

答えて

9

あなたはファイルから読み込み中でもあります。それをしないでください。代わりに、NamedTemporaryFileに書き込んでから、renameを書き込みを終えて元のファイルに上書きして閉じる必要があります。

またはファイルのサイズが小さいことが保証されている場合は、あなたがして、ファイルを閉じて、あなたがしたい行を変更し、それを書き戻し、それのすべてを読み取るためにreadlines()を使用することができます。

def editline(file,n_line,text): 
    with open(file) as infile: 
     lines = infile.readlines() 
    lines[n_line] = text+' \n' 
    with open(file, 'w') as outfile: 
     outfile.writelines(lines) 
2

一時ファイルを使用:

import os 
import shutil 


def writeline(filename, n_line, text): 
    tmp_filename = filename + ".tmp" 

    count = 0 
    with open(tmp_filename, 'wt') as tmp: 
     with open(filename, 'rt') as src: 
      for line in src: 
       count += 1 
       if count == n_line: 
        line = line.replace(str(line), text + '\n') 
       tmp.write(line) 
    shutil.copy(tmp_filename, filename) 
    os.remove(tmp_filename) 


def create_test(fname): 
    with open(fname,'w') as f: 
     f.write('1 \n2 \n3 \n4 \n5') 

if __name__ == "__main__": 
    create_test('writetest.txt') 
    writeline('writetest.txt', 4, 'This is the fourth line') 
関連する問題