ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Fri, 05 Jan 2024 13:36:13 +0100How to save a list of graphs into a graph6 format file?https://ask.sagemath.org/question/75320/how-to-save-a-list-of-graphs-into-a-graph6-format-file/The following is the code for finding connected graphs with 8 vertices, 10 edges, and a matching number of 3.
gen = graphs.nauty_geng("8 10 -c ")
L=[]
for g in gen:
if len(g.matching()) ==3:
L.append(g)
I want to save these graphs in Graph6 format into a file. I know Mathematica has a convenient command for this.
```Export["somefile.g6",graphList,"Graph6"]```
Does SageMath have a similar command? I can currently only write it like following. I wonder if there is a simpler solution.
file_path = "matching_graphs.g6"
with open(file_path, 'w') as file:
for G in L:
file.write(G.graph6_string() + '\n')Fri, 05 Jan 2024 08:42:53 +0100https://ask.sagemath.org/question/75320/how-to-save-a-list-of-graphs-into-a-graph6-format-file/Answer by rburing for <p>The following is the code for finding connected graphs with 8 vertices, 10 edges, and a matching number of 3.</p>
<pre><code>gen = graphs.nauty_geng("8 10 -c ")
L=[]
for g in gen:
if len(g.matching()) ==3:
L.append(g)
</code></pre>
<p>I want to save these graphs in Graph6 format into a file. I know Mathematica has a convenient command for this. </p>
<p><code>Export["somefile.g6",graphList,"Graph6"]</code></p>
<p>Does SageMath have a similar command? I can currently only write it like following. I wonder if there is a simpler solution.</p>
<pre><code>file_path = "matching_graphs.g6"
with open(file_path, 'w') as file:
for G in L:
file.write(G.graph6_string() + '\n')
</code></pre>
https://ask.sagemath.org/question/75320/how-to-save-a-list-of-graphs-into-a-graph6-format-file/?answer=75328#post-id-75328That's already pretty short. Here is an alternative one-liner using [`graphs_list.to_graph6`](https://doc.sagemath.org/html/en/reference/graphs/sage/graphs/graph_list.html#sage.graphs.graph_list.to_graph6) and `print`:
sage: print(graphs_list.to_graph6(L), file=open('matching_graphs.g6', 'w'), end='')
This builds a big string in memory though, so it wouldn't be suitable for gigantic lists.
We could also mimic Mathematica by defining a somewhat generic `export` function:
def export(filename, object_list, method_name):
with open(filename, 'w') as f:
for obj in object_list:
f.write(attrcall(method_name)(obj) + '\n')
Then we can do:
sage: export('matching_graphs.g6', L, 'graph6_string')
Fri, 05 Jan 2024 13:36:13 +0100https://ask.sagemath.org/question/75320/how-to-save-a-list-of-graphs-into-a-graph6-format-file/?answer=75328#post-id-75328