I've been writing a python script to help me clear up some files that contain outdated code, while also serving as a way to learn python. These files have sections of code surrounded with tags on their own lines, I need it to remove both the tags and everything within. While this largely applies to XML documents I am also using this script for several other file types, so XML specific solutions aren't suitable.
I have a working script already but it doesn't look like the most elegant or efficient solution by far, so I would like to see how I can improve it.
Script is called as python
cleanup.py startDeleteTag stopDeleteTag where the last two arguments are the locations where the code should be deleted and stop being deleted respectfully.
import os, sys def clearFile(path, beginDelete, stopDelete): path = os.path.join(path, "fileName.xml") input = open(path, "r") lines = input.readlines() input.close() currentFlag = False nextFlag = False output = open(path, "w") for line in lines: if nextFlag == True: nextFlag = False deleteFlag = False if beginDelete in line: deleteFlag = True elif stopDelete in line: nextFlag = True if deleteFlag == False: output.write(line) thisDirectory = os.getcwd() for start, dirs, files in os.walk(thisDirectory): for f in files: if f == "fileName.xml": clearFile(thisDirectory, sys.argv, sys.argv)
This is the part of the script that checks each line for the start of the section to be deleted (
stopDelete). Because this would leave the end tag in the file I have to use a couple of booleans to specify when the current line needs to be removed but the next line shouldn't be. As an extra, is there a way to improve this to further check for tags that may be on the same line as body of the code? This isn't currently an issue but I'm curious how I would do it if I needed to in future.
As requested, and example file input would look like this:
<good> keep this </good> <bad> delete this </bad> <good> keep this <bad> delete this </bad> </good>
And this would produce the output:
<good> keep this </good> <good> keep this </good>