Delete blocks from DXF file #1184
Replies: 3 comments 2 replies
-
If you are new to DXF, do not blindly delete objects in the DXF file! The DXF file format is complex and internal structures can easily be destroyed. I will look into the problem when I have time. |
Beta Was this translation helpful? Give feedback.
-
So, I've looked into your "problem" and I can't really help you because you're trying to shoot yourself in the foot and You have bypassed one of the few safeguards in the library: doc.blocks.delete_block(name=block_name, safe=False)
# ^^^^^^^^^^ The current state of the method allows you to destroy required layouts even when This version deletes only blocks that are referenced in modelspace: import ezdxf
doc = ezdxf.readfile("0_Tower_B_Coord_25_Floor_structural.dxf")
msp = doc.modelspace()
referenced_blocks = set()
for insert in msp.query("INSERT"):
referenced_blocks.add(insert.dxf.name)
msp.delete_entity(insert)
for block_name in referenced_blocks:
try:
doc.blocks.delete_block(name=block_name, safe=True)
except ezdxf.DXFBlockInUseError:
pass
# Safeguard for users who do not want to export destroyed DXF documents
report = doc.audit()
if not report.has_errors:
doc.saveas("blocks_deleted.dxf")
else:
report.print_error_report() |
Beta Was this translation helpful? Give feedback.
-
This is a different solution that utilizes the import ezdxf
from ezdxf import blkrefs
doc = ezdxf.readfile("0_Tower_B_Coord_25_Floor_structural.dxf")
ref_counter = blkrefs.BlockReferenceCounter(doc)
unreferenced_blocks = set()
for block in doc.blocks:
if not block.is_alive or block.is_any_layout:
continue
count = ref_counter.by_name(block.name)
if count == 0:
# DO NOT DELETE BLOCK WHILE ITERATING!
unreferenced_blocks.add(block.name)
for block_name in unreferenced_blocks:
# The blkrefs.BlockReferenceCounter counts ALL KNOWN references, it should be safe
# to destroy these blocks without safeguards (no guarantee for that!):
doc.blocks.delete_block(block_name, safe=False)
report = doc.audit()
if not report.has_errors:
doc.saveas("unused_blocks_purged.dxf")
else:
report.print_error_report() This code reduces the filesize from 86.5MB to 2.3 MB, like the nested PURGE command in BricsCAD. |
Beta Was this translation helpful? Give feedback.
-
Hello ezdxf community:
I am new to
ezdxf
. I am trying to delete all the blocks from DXF file and save the same. However, I get an error:AttributeError: 'BlockRecord' object has no attribute 'dxf'
. Here is the link to the DXF file.Below is the code:
Any help is appreciated.
Beta Was this translation helpful? Give feedback.
All reactions