简体   繁体   中英

with Networkx, how to write graphml and other format into a string, instead of a file?

I'm using networkx very superficially. It's easy to write a graph to a file, like graphml, but how can I save it into a string without bothering the file system?

Its doc says it is possible.

Most of the formats also have a "generator". So you can do it this way without using StringIO:

In [1]: import networkx as nx

In [2]: G=nx.path_graph(4)

In [3]: s='\n'.join(nx.generate_graphml(G))

In [4]: print s
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key attr.name="name" attr.type="string" for="graph" id="d0" />
  <graph edgedefault="undirected">
    <data key="d0">path_graph(4)</data>
    <node id="0" />
    <node id="1" />
    <node id="2" />
    <node id="3" />
    <edge source="0" target="1" />
    <edge source="1" target="2" />
    <edge source="2" target="3" />
  </graph>
</graphml>

Just as larsmans commented, it's possible using StringIO :

import networkx as nx
import StringIO
import itertools

g = nx.Graph()

edges = itertools.combinations([1,2,3,4], 2)
g.add_edges_from(edges)

# File-like object
output = StringIO.StringIO()

nx.write_graphml(g, output)

# And here's your string
gstr = output.getvalue()
print gstr
output.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM