简体   繁体   中英

Python not over-writing file

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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM