f1=open(r"E:\f2.txt","r+")
lines = f1.readlines()
f1.seek(0)
#f1.truncate()
for line in f1:
if 'SN 07689630' in line:
line=line.replace(line,"blank")
f1.write(line)
break
I have been using this code but its not working
f1=open(r"E:\f2.txt","r+")
lines = f1.readlines()
f1.seek(0)
#f1.truncate()
for line in f1:
if 'SN 07689630' in line:
line=line.replace(line,"blank")
f1.write(line)
break
I have been using this code but its not working
You are getting out of the for loop too soon by using the break statement. Im sure, the text entry 'SN 07689630' is not on the first line of your file, and the condition given for the if statement was not met, then you exit the for loop right away. Take out the break statement and see what happens. My guess is it will append a new line that has the word "blank"
One solution is to open again a new file pointer with a same filename in write mode similar to this:
f1=open("sample.txt","r")
lines = f1.readlines()
f1.close()
f1 = open("sample.txt","w")
for line in lines:
if 'SN 07689630' in line:
line="blank\n"
f1.write(line)