Search code examples
pythonsvgprogramming-languages

How to modify the contents of an .SVG file with Python?


  1. I have a .svg file with example contents: <svg style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.001" /></svg>

  2. I now want to use Python to directly edit the .svg file and change style="fill:#000000; to my desired color and save it., but I am not sure how to go about this, I have tried a lot of libraries but none do what I need.


Solution

  • Try this: https://pythonexamples.org/python-replace-string-in-file/

    #read input file
    fin = open("data.svg", "rt")
    
    #read file contents to string
    data = fin.read()
    
    #replace all occurrences of the required string
    data = data.replace('style="fill:#000000;', 'style="fill:#FF0000;')
    
    #close the input file
    fin.close()
    
    #open the input file in write mode
    fin = open("data.svg", "wt")
    
    #overrite the input file with the resulting data
    fin.write(data)
    
    #close the file
    fin.close()