I’d like to order the out put in a specific way to csv. So grouped by type, then a line break before the next type. I don’t however…have a clue where to start
I am no expert in programming in python so, my way would be a very crude one. (I cant see the script you mentioned).
Anyway. In the loop that writes the rows to the file, you need to track the “Ref” character. In my projects I have references with one and two characters… e.g. R, C but also FB and RN. Anyway, track the characters and on change, insert an empty line before writing the new Ref type.
ref = 'first'
for c in components:
# get components character, try 2 first
# fallback to use first only
# DOES not work if you have refs like REL101
if c.getRef()[:2].isalpha():
ref_n = c.getRef()[:2]
else:
ref_n = c.getRef()[:1]
if ref == 'first':
ref = ref_n
else:
if ref_n != ref:
# insert separator here
writerow(out, [""])
ref=ref_n
As I said, I use crude coding so there probably are more elegant ways… I presume that the list is already sorted… Not sure if I missed the point there. But as far as I remember there are examples with such sorted component list.
import csv
# Sample list of components (replace this with your actual data)
components = [
{"type": "Resistors", "name": "R1", "value": "100k"},
{"type": "Resistors", "name": "R2", "value": "1M"},
{"type": "Capacitors", "name": "C1", "value": "10nF"},
{"type": "Capacitors", "name": "C2", "value": "100uF"},
{"type": "Diodes", "name": "D1", "value": "1N4007"},
# Add more components here...
]
# Dictionary to group components by type
component_groups = {}
# Group components by type
for component in components:
component_type = component["type"]
if component_type not in component_groups:
component_groups[component_type] = []
component_groups[component_type].append(component)
# Function to write the components to CSV with a blank line after each group
def write_components_to_csv(filename):
with open(filename, mode="w", newline="") as file:
writer = csv.writer(file)
for component_type, components_list in component_groups.items():
for component in components_list:
writer.writerow([component["name"], component["value"]])
writer.writerow([]) # Add a blank row after each group
# Call the function and provide the output file name (e.g., "components.csv")
write_components_to_csv("components.csv")
Remember to replace the **components** list with your actual data before running the script.