import sys import re from xml.etree import ElementTree from pathlib import Path import os def add_bounds(directory): for path in Path(directory).rglob("*.svg"): if path.name.startswith("z_"): print("Renamed {0}".format(path)) renamed = path.with_name(path.name[2:]) if os.path.exists(renamed): os.unlink(renamed) os.rename(path, renamed) for path in Path(directory).rglob('*.svg'): tree = ElementTree.ElementTree() parsed = tree.parse(path) if "width" not in parsed.attrib: print(f"Rewriting {path}") width, height = parsed.attrib["viewBox"].split(" ")[-2:] # I'd rather avoid mangling the XML files by parsing them first # XML is awful and we never should have invented it :( with open(path, "r", encoding="utf-8") as file: data = file.read() data = re.sub('viewBox="0 0', f'width="{width}" height="{height}" viewBox="0 0', data) with open(path, "w", encoding="utf-8") as file: file.write(data) if __name__ == "__main__": add_bounds(sys.argv[1])