Blog / Python

Python Automation: Batch Modification of SVG Files by Removing Class Attributes in All Files

Hey there! Do you have a bunch of SVG files that you want to modify, but they all have different classes? Well, fear not my friend, because I've got just the thing for you - a Python script to remove all the classes from all the files in a folder!

In this tutorial, I'll walk you through the steps to create a Python script that will loop through all the SVG files in a folder, remove all the classes, and save the modified files back to the folder. It's super easy to do, and you don't even need to know a lot of programming to get started.

So if you're ready to learn how to automate your SVG class removal, let's get started!

Here's a Python script that should do what you're looking for. Just create a file class_remover.py paste this:

import os
import re

# specify the directory containing the SVG files
directory = "."

# loop through all the SVG files in the directory
for filename in os.listdir(directory):
    if filename.endswith(".svg"):
        # read the contents of the file
        with open(os.path.join(directory, filename), "r") as f:
            contents = f.read()
        
        # remove all occurrences of the class attribute
        contents = re.sub(r'class="[^"]*"', '', contents)
        
        # write the modified contents back to the file
        with open(os.path.join(directory, filename), "w") as f:
            f.write(contents)

Now just run in your terminal python class_remover.py and see the magic!

This script uses the os and re modules to loop through all SVG files in the current directory, remove all occurrences of the class attribute, and write the modified contents back to the file.

The regular expression r'class="[^"]*"' matches any class attribute with its value enclosed in double quotes, and replaces it with an empty string.