0

I am trying to delete one line of code from a text file and update it to a new value.

I have user inputted value in "line1" and "line2" and trying to update value of line1 to line2. When I used below code,

f1=open("test.txt","a+")
f2=open("test.txt","a+")
for line in f1:
    f2.write(line.replace(line1,line2))
f1.close()
f2.close()

It doesn't replace the value of line1 to line2 but creates another line of line2. So output in my text file is value of line1 value of line2

How can I change this code to replace the value of line1 to line2 and delete the value of line1 from the text file?

Thanks!

Hee Park
  • 11
  • 1
  • Welcome to StackOverflow. About your question, what do you have tried so far? – felipsmartins Feb 18 '20 at 00:13
  • @Flux I tried this earlier, but instead of updating the user's information that I wanted to update, this code actually deleted information that should be updated. Thank you for the direction! – Hee Park Feb 18 '20 at 00:41
  • @felipsmartins I have tried different things. but I don't have a lot of knowledge of python, so this is very hard even though it might be very easy for some people. I've been stuck at this since yesterday. – Hee Park Feb 18 '20 at 00:43
  • See the answers to https://stackoverflow.com/questions/4746190/find-and-replace-within-a-text-file-using-python – Flux Feb 18 '20 at 00:52
  • @Flux Thanks Flux! but this deleted everything in the file again. – Hee Park Feb 18 '20 at 01:04

0 Answers0