简体   繁体   中英

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM