如何使用Python修改.SVG文件中的样式及内容
实现方案
你需要修改SVG文件中style属性里的fill颜色值,下面是两种可直接落地的实现方式:
方案1:直接字符串替换(适合结构固定的SVG文件)
代码最简无需依赖任何第三方库,处理速度快,仅适合格式确定、不会在其他位置出现相同匹配文本的SVG文件:
# 配置参数 svg_path = "你的文件路径.svg" target_color = "#ff0000" # 替换为你需要的目标颜色 old_str = 'style="fill:#000000;' new_str = f'style="fill:{target_color};' # 读取并修改内容 with open(svg_path, 'r', encoding='utf-8') as f: content = f.read() content = content.replace(old_str, new_str) # 保存修改后的文件 with open(svg_path, 'w', encoding='utf-8') as f: f.write(content)
方案2:XML解析修改(更稳妥,无误替换风险)
SVG本身是标准XML格式,用Python自带的XML解析库可以精准定位属性修改,不会误改其他内容,也不需要安装第三方依赖:
import xml.etree.ElementTree as ET # 配置参数 svg_path = "你的文件路径.svg" target_color = "#ff0000" # 替换为你需要的目标颜色 # 解析SVG文件,注册默认命名空间避免保存后标签前缀异常 ET.register_namespace('', 'http://www.w3.org/2000/svg') tree = ET.parse(svg_path) root = tree.getroot() # 精准修改style属性中的fill值 if 'style' in root.attrib: style_items = root.attrib['style'].split(';') new_style = [] for item in style_items: if item.strip().startswith('fill:'): new_style.append(f'fill:{target_color}') else: new_style.append(item) root.attrib['style'] = ';'.join(new_style) # 保存修改后的文件 tree.write(svg_path, encoding='utf-8', xml_declaration=True)
内容的提问来源于stack exchange,提问作者name
相关产品推荐
相关产品推荐

