Hello everyone, I have an autocad file with several already existing blocks. I would like to add two new attributes to all the blocks of a certain Layer. Now I am at an early stage and I am testing my code with a file with only one block but I am not able to access the Block definition for correctly caling the AddAttribute function.
from pyautocad import aDouble
import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
# Document object
blocks= acad.ActiveDocument.Blocks
res = blocks.AddAttribute(50, 0, "test", aDouble(200, 100, 0), "TEST", "TEST TEXT")
Solved! Go to Solution.
Solved by jayhar. Go to Solution.
To add attributes to all blocks on a certain layer in an AutoCAD file using Python and the `pyautocad` library, you can follow these steps:
1. Import the required modules:
```python
from pyautocad import aDouble
import win32com.client
```
2. Connect to the AutoCAD application and open the active document:
```python
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
```
3. Get the blocks collection and iterate over all the blocks:
```python
blocks = doc.Blocks
for block in blocks:
# Check if the block is on the desired layer
if block.Layer == "YourLayerName":
# Add the attributes to the block
res = block.AddAttribute(
50, # Tag value
0, # Invisible attribute flag
"test", # Prompt
aDouble(200, 100, 0), # Insertion point
"TEST", # Tag
"TEST TEXT" # Default value
)
```
Make sure to replace `"YourLayerName"` with the name of the layer you want to target. This code will add the attributes to all the blocks on that layer. You can modify the attribute parameters as per your requirements.
Note: The code assumes that you have already installed the `pyautocad` library and have a working installation of AutoCAD.
@jayharwhy I cannot run the same code with pyautocad? Everything works except the Layer research. How can I check the layer with pyautocad?
If that is not possible, how can I just shut down the other layers from the model Space and work only with layers I am interested too? Luckily I do not have the same block in more layers
Can't find what you're looking for? Ask the community or share your knowledge.