0
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

yash
  • 1,357
  • 2
  • 23
  • 34
Pooja
  • 1
  • this might help you OP https://stackoverflow.com/a/1388570/4410922 – yash Nov 07 '17 at 05:45
  • Welcome to Stackoverflow! Please have a look at [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and update your question. Python functions using indentation, so without a proper format we can not understand your code. – arshovon Nov 07 '17 at 05:51

1 Answers1

0

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)