NX Journal Save the list of assemblies as csv

2019/12/13 categories:NX Journal| tags:NX Journal|Python|

I wrote a program to output the assembly tree list and parts list in csv in NX Journal.

I use “GetChildren” and “IsSuppressed” of the “component” class to get the child parts and save them as a CSV file with csv of the python standard library. Put the attribute you want to get in “attr”, the key of the dictionary is the attribute to get from the component, and the value will be the name used when saving CSV. The CSV file is saved as “parts_list.csv” and “tree_list.csv” directly under the D drive.

The output parts list is a list of parts counted without duplication. Components that are suppressed in both the tree list and parts list are skipped.

Python Code

import csv
import NXOpen

attr = {
    "part_number":"Part number",
    "part_name":"Part name",

def main():
    theSession  = NXOpen.Session.GetSession()
    workPart = theSession.Parts.Work
    theComponent = workPart.ComponentAssembly.RootComponent
    rank1 = 0
    parts_list = {}

    # Add assembly top
    tree_list = [ [rank1, theComponent] ]

    # Recursively get the attributes of child parts
    recursion( theComponent, rank1 + 1, tree_list, parts_list )

    # Csv output tree list
    csv_tree_list = [ [attr[key] for key in attr.keys()] ]
    for tmp in tree_list:
        component = [tmp[0]]
        for key in attr.keys():
                component.append( tmp[1].GetStringAttribute(key) )
    saveCSV("D:\\tree_list.csv", csv_tree_list)
    # Csv output parts list
    csv_parts_list = [ [key, parts_list1[key]] for key in parts_list1 ]
    saveCSV("D:\\parts_list.csv", csv_parts_list)

def saveCSV(filename, lists):
    with open(filename, "w", encoding="cp932") as f:
        writer = csv.writer(f, lineterminator="\n")

def recursion( component1, rank2, tree_list2, parts_list2 ):
    for child1 in component1.getChildren():
        # Skip if suppressed
        if child1.IsSuppressed:
        # Add to tree list
        tree_list2.append( [rank2, child1] )
        # Add to parts list
        part_no = component2.GetStringAttribute(attr["Part number"])
        if part_no in parts_list2.keys:
            parts_list2[part_no] = parts_list2[part_no] + 1
            parts_list2[part_no] = 1
        # Recursive execution
        recursion( child1, rank2 + 1, tree_list2, parts_list2 )

if __name__ == '__main__':

Share post

Related Posts