I’m trying to write a script that can read several .xml files within a directory
When a specific string is found (every file has this script), I need it to delete all content after that string and replace it all with new content (this can be pulled in from another file if that’s easier).
There are numerous lines being deleted/written here.
At the moment I am manually going through the files and deleting all text after the string, then saving the files and running this python script:
import fileinput
import sys
import os
os.chdir("F:\Desktop\PyTest")
rootdir='F:\Desktop\PyTest'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file, 'r')
lines=f.readlines()
f.close()
f=open(file, 'a')
f.write("\n <Text>Lorem Ipsum</Text>")
f.write("\n <Text>Lorem Ipsum</Text>")
f.write("\n <Text>Lorem Ipsum</Text>")
f.write("\n <Text>Lorem Ipsum</Text>")
f.close
It took me a while to piece this together from tutorials, and although I’ve managed to find tutorials to search for a specific string and to replace it, I haven’t been able to erase all content after a string and replace with new.
Any advice would be greatly appreciated 🙂
Doesn’t have to be in Python, but I am running a Windows environment.
This is notably not the fastest implementation for large files, but should work.
Replace ‘criteria’ for the string you are looking for.
To be clear:
Means: