返回 BIM 与 IFC 博客
工具与对比 · 2026-06-03 · 8 分钟
用 Python 和 IfcOpenShell 读取 IFC 属性集
你需要把 IFC 中的属性数据(工程量、分类、自定义 Pset)提取出来,放进电子表格、数据库或 QA 检查中。借助 IfcOpenShell,这只需要几行 Python 代码。下面是一份实用手册,还包括那个大家都希望早点发现的 get_psets 捷径。
用 Python 和 IfcOpenShell 读取 IFC 属性集 — IFC Viewer Online article cover
每个与 BIM 打交道的开发者,迟早都要从 IFC 中取出数据:算量需要构件工程量,台账需要分类,QA 规则需要自定义属性集。IfcOpenShell 是一个开源库,让你能在 Python 中轻松完成这些工作。本文给出一条实用的路径:先用手动方式理解数据结构,再介绍只需要数据时的一行捷径。
打开文件并查找构件
import ifcopenshell
model = ifcopenshell.open("model.ifc")
# All walls in the file
walls = model.by_type("IfcWall")
print(f"{len(walls)} walls")
# A single element by its GlobalId
el = model.by_guid("3LYa_FRDj3zhLfyYoQv6Jr")
手动方式(理解数据结构)
属性集并不直接存储在构件上,而是通过关系挂接到构件上。构件的 IsDefinedBy 中保存着 IfcRelDefinesByProperties 关系,每个关系都指向一个属性集(即 RelatingPropertyDefinition)。在属性集内部,HasProperties 列出了各个属性,其中大多数是带有 Name 和 NominalValue 的 IfcPropertySingleValue。
wall = walls[0]
for rel in wall.IsDefinedBy:
if rel.is_a("IfcRelDefinesByProperties"):
pset = rel.RelatingPropertyDefinition
if pset.is_a("IfcPropertySet"):
print(pset.Name) # e.g. "Pset_WallCommon"
for prop in pset.HasProperties:
if prop.is_a("IfcPropertySingleValue") and prop.NominalValue:
print(f" {prop.Name} = {prop.NominalValue.wrappedValue}")
捷径:get_psets()
手动遍历值得理解一次,但实际工作中请使用工具函数:ifcopenshell.util.element.get_psets() 会把构件上的所有属性集作为普通字典返回,键是 Pset 名称,值是属性字典。这比自己遍历关系要可靠得多。
import ifcopenshell.util.element as ue
psets = ue.get_psets(wall)
# {'Pset_WallCommon': {'IsExternal': True, 'FireRating': 'REI 60', 'id': 1234}, ...}
fire_rating = psets.get("Pset_WallCommon", {}).get("FireRating")
# Quantities only (areas, volumes, lengths)
qtos = ue.get_psets(wall, qtos_only=True)
把所有构件导出为表格
import csv
import ifcopenshell.util.element as ue
with open("elements.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["GlobalId", "Class", "Name", "Pset", "Property", "Value"])
for el in model.by_type("IfcBuildingElement"):
for pset_name, props in ue.get_psets(el).items():
for key, value in props.items():
if key == "id":
continue
writer.writerow([el.GlobalId, el.is_a(), el.Name, pset_name, key, value])
脚本读取与可视化查看的分界
Python 非常适合在流水线中批量提取数据和自动化 QA。但如果你想亲眼看看某个构件上的属性集,或者要把文件交给不写代码的人,那么点击构件即可显示其 Pset 的查看器会更快。两者相辅相成:用脚本做批量检查,用可视化方式查看特殊情况。
可视化查看 Pset
打开双层公寓模型,点击任意构件即可查看其完整的属性集。这与 get_psets() 返回的数据相同,而且不用写任何代码。
IFC2x3 · 2.4 MB
打开交互式 IFC 查看器
用 Python 和 IfcOpenShell 读取 IFC 属性集