2016-04-22 123 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':代码编译好了(即使它不能删除前面的文本),但是如果我'如果count == n_line:',文件结束很多垃圾。

Answer工作,但我想知道我的代码有什么问题,为什么我不能读写。谢谢!

回答

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')