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))
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!
source share