As mentioned by me in my previous blog post I will keeps discussing workflows and operations that can be implemented with the pywin32 module in Python. In this post I will show how you can delete AutoCAD objects with pywin32 and pyautocad in Python. I have also written various other posts covering both pyautocad and pywin32. E.g. I have covered topics such as: How to handle solid objects with pyautocad, how to implement AutoCAD operations with pyautocad, how to integrate pywin32 with AutoCAD, as well as workflow-related content such as e.g. Python data structures for AutoCAD object organization.
Deleting objects using pyautocad
Setting up environment for pyautocad
As usual, we will set up our environment for integrating python with AutoCAD.
from pyautocad import Autocad acad = Autocad(create_if_not_exists=True)
Using delete method provided by pyautocad
To delete objects, I have created some objects on our AutoCAD template as shown in Figure 1 below:
Now we will use a very simple utility of pyautocad called iter_objects(), to loop through every object from the template.
for object in acad.iter.objects() object.Delete()
On implementing this command, all the objects will be deleted.
Filtering out objects for deletion using pyautocad
Sometimes we need to filter our objects before deleting i.e. suppose if we want to delete only the circle from the template as shown in Figure 1, then we can use the following methodology.
for object in acad.iter_objects(object_name_or_list="AcDbCircle"): object.Delete()
Deleting objects using pywin32 (win32com.client)
Setting up environment for pywin32
import win32com.client acad = win32com.client.Dispatch("AutoCAD.Application") acad.Visible = True acadModel = acad.ActiveDocument.ModelSpace
We will be using the same figures as given in Figure 1.
Deleting objects from AutoCAD template using pywin32
While using pywin32, we have a very direct approach to code for iterating through objects from the AutoCAD template.
for object in acadModel: object.Delete()
Filtering objects for deletion while working with pywin32
Filtering out objects while using pywin32 takes just an “if statement”. Let’s look at the same.
for object in acadModel: if object.ObjectName == "AcDbCircle": object.Delete()
Civil engineer interested in automation in core subjects such as civil, mechanical and electrical, using IT skills comprising cloud computing, devops, programming languages and databases along with the technical skills gained while working as a civil engineer since past 3 years.