How to remove a string from a text file in Python?

I am trying to make code to overwrite a specific line from a .txt file. I can write in the line I want, but I cannot erase the previous text in the line.

Here is my code:
(I try a couple of things)

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) 

You can use this code to create a test file for testing:

 with open('writetest.txt','w') as f: f.write('1 \n2 \n3 \n4 \n5') writeline('writetest.txt',4,'This is the fourth line') 

Edit: for some reason, if I use 'if count == 5:', the code compiles fine (even if it does not erase the previous text), but if I do 'if count == n_line:', the file ends up with a lot of garbage.

The answers work, but I would like to know what the problems are with my code, and why I can not read and write. Thanks!

+6
source share
2 answers

You read from a file and also write it. Do not do this. Instead, you should write NamedTemporaryFile , and then rename over the source file after you finish writing and closing it.

Or, if the file size is guaranteed to be small, you can use readlines() to read it all, then close the file, change the line and write it back:

 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) 
+9
source

Use temporary file:

 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') 
+2
source

All Articles