As we mentioned in our previous blog post, we will be discussing more on the pywin32 module, here is our new blog post. In this blog post, we will be discussing a very small topic i.e. how to delete objects from an AutoCAD template with pyautocad as well as with pywin32.
1. Deleting objects using pyautocad:
1.1 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)
1.2 Using delete method with 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.
1.3 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.1, then we can use the following methodology.
for object in acad.iter_objects(object_name_or_list="AcDbCircle"): object.Delete()
2. Deleting objects using pywin32 (win32com.client)
2.1 Setting up environment for pywin32
As we have discussed initiating an AutoCAD template using pywin32 in our previous blog, we will set up our work environment to integrate python and AutoCAD.
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.1.
2.2 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()
Considering the difference between the usage of pyautocad and pywin32 while deleting objects, we found pywin32 to be more efficient.
2.3 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.