I have an xml file that is 1000 lines long, I need to replace all Mathew with Kasper in that xml file. I am able to do that successfully if I read all lines of the xml file(test1.xml) and write the contents to another file(test2.xml) but If I dont want to read all the lines rather read only those lines in which there is Mathew and and then only update that content in the file is that possible? This is my latest code that works but it reads everyline.
#Location to the xml file
XMLFile = "test1.xml"
COPYFILE = "test2.xml"
content = open(XMLFile, "r")
with open(COPYFILE, 'w') as write_file:
# Read all lines in the file one by one
for line in content:
# For each line, check if line contains the word
if 'and' in line:
line = line.replace("Mathew", "Kasper")
if __name__ == "__main__":
I can add an if statement: If 'and ’ in line: but then also I would have to write every line of the file content to the new file, isnt it possible to use the same file test1.xml and only update that file by only updating the needed changes and not touching anything else and let the remaining content stay as is.