1

I am trying to overwrite individual lines of a particular file by replacing certain keywords within the line. I have already looked into multiple questions and most of the answers were showing what I have already implemented. Following is the code:

with open(fileLocation,"r+") as openFile:
    for line in openFile:
        if line.strip().startswith("objectName:"):
            line =  re.sub(initialName.replace(".qml",""),camelCaseName.replace(".qml",""),line)
            print line
            openFile.write(line)

    openFile.close()
  • Please also explain what is going wrong here. Also, you don't need to explicitly close the file if you've opened it using `with`. – BlackVegetable Feb 14 '17 at 15:02
  • Not able to overwrite the line which is being replace. File contents remains the same. – Himanshu Verma Feb 14 '17 at 15:05
  • The content you would like to write is being correctly printed to the console, right? At a glance, I'd think this code is appending to the end of a file, not actually replacing those lines. – BlackVegetable Feb 14 '17 at 15:06
  • Yeah contents are being correct printed. I have checked the end of file and there's no appending. – Himanshu Verma Feb 14 '17 at 15:08
  • Consider this answer: http://stackoverflow.com/a/17141572/758446 – BlackVegetable Feb 14 '17 at 15:14
  • So it won't be possible to overwrite file line by line? Also how should I check whether the line starts with "ObjectName:"? – Himanshu Verma Feb 14 '17 at 15:17
  • 1
    You can load the entire file into memory (unless it is too large) and then mutate that file-in-memory via a for loop as you have it, and then write all the lines, both those you change, and those you don't, to the output file. you can even make the output file the same name the input file was, effectively overwriting it. – BlackVegetable Feb 14 '17 at 15:19
  • Is it possible if you can write a sample code for reference? – Himanshu Verma Feb 14 '17 at 15:24

1 Answers1

1

You could save the text of the file to a string, save the changes to that strings and write the text once you are finished editing :)

finalText = ""  # Here we will store the complete text

with open(fileLocation, "r") as openFile:
    for line in openFile:
        if line.strip().startswith("objectName:"):
            line = ... # do whatever you want to do with the line.
        finalText += line

and just do the following right after that:

with open(fileLocation, 'w') as openFile:
    openFile.write(finalText)
mikelsr
  • 457
  • 6
  • 13
  • It worked! Thanks a lot!! Though I am still wondering what is wrong in my code? – Himanshu Verma Feb 14 '17 at 15:33
  • 1
    The reading and writing to the same file while iterating through said file likely caused your problems. However, I'm surprised no explicit exception was raised. Regardless, this is what I was referring to above. +1 – BlackVegetable Feb 14 '17 at 16:07