Reputation: 13
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()
Upvotes: 1
Views: 41
Reputation: 457
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)
Upvotes: 1