I am trying to replace a string with a new string in a python file and write the new string permanently to it. When I run the below script it removes part of the string and not all of it. The string in the file is:
self.id = "027FC8EBC2D1"
And the script I have to replace the string is:
def edit():
o = open("test.py","r+") #open
for line in open("test.py"):
line = line.replace("027FC8EBC2D1","NewValue")
o.write(line)
o.close()
edit()
Thanks for any help.
The proper way to do (actually simulate😉 “in-place substitution” on text files with Python is the fileinput module:
Note a couple of crucial details wrt the other answer that suggests the same module:
input‘s first argument must be a list of filenames (not a string!), and, you do have toprintevery line that you want in the resulting file (fileinputredirects standard output to perform — actually simulate — the “overwrite in-place” effect).A final small but not-negligible detail: the comma at the end of the
printstatement is to avoid adding another newline at the end (since eachlinealready ends with a newline!-).