I realize this is not really sophisticated, but if, and only if your XML is formatted exactly as you've shown me (with the tabs and newlines exactly like that), then you can just use the script I just made you:
import os
from sys import exit
file_to_fix = input("file to fix: ")
if not os.path.exists(file_to_fix):
print("File doesn't exist.")
exit(1)
if not os.path.isfile(file_to_fix):
print("Path is not file.")
exit(1)
dry_run = None
while dry_run == None:
dry_run_read = input("Dry run (y/n)? ")
if dry_run_read.lower() == "y":
dry_run = True
else:
if dry_run_read.lower() == "n":
dry_run = False
else:
print("Invalid input, either y or n.")
file = open(file_to_fix, "r")
file_contents = file.read()
lines = file_contents.split("\n")
for index, line in enumerate(lines):
if line.startswith(" "):
if line[len(" "):] == "<text>":
if dry_run:
print("Would've fixed line " + str(index + 1) + ".")
else:
print("Fixed line " + str(index + 1) + ".")
lines[index] = " <comment>"
file.close()
if not dry_run:
file = open(file_to_fix, "w")
print("Writing file...")
file.write("\n".join(lines))
file.close()
print("Wrote file.")
print("Fixed file '" + file_to_fix + "'.")
else:
print("Would've written file.")
print("would've fixed file '" + file_to_fix + "'.")
Proof that it works (my terminal output):
/tmp/tmp.2MoTo46mcK via 🐍 v3.14.3
❯ cat file_to_fix.xml
<body>
<text>
<text>
second level text before
</text>
main text
<text>
second level text after
</text>
</text>
</body>
/tmp/tmp.2MoTo46mcK via 🐍 v3.14.3
❯ python patcher.py
file to fix: file_to_fix.xml
Dry run (y/n)? y
Would've fixed line 3.
Would've fixed line 7.
Would've written file.
would've fixed file 'file_to_fix.xml'.
/tmp/tmp.2MoTo46mcK via 🐍 v3.14.3 took 3s
❯ python patcher.py
file to fix: file_to_fix.xml
Dry run (y/n)? n
Fixed line 3.
Fixed line 7.
Writing file...
Wrote file.
Fixed file 'file_to_fix.xml'.
/tmp/tmp.2MoTo46mcK via 🐍 v3.14.3 took 4s
❯ cat file_to_fix.xml
<body>
<text>
<comment>
second level text before
</text>
main text
<comment>
second level text after
</text>
</text>
</body>
/tmp/tmp.2MoTo46mcK via 🐍 v3.14.3
❯ echo "yay"
yay
Note that this will work only and only if the file is formatted EXACTLY as you've shown me, I cannot stress this enough.
But yeah as you can see, works with your example.
Best of luck and good day to you :)
Reese Reed
· 0 rep
· 9 hours ago