NetworkX: write graph in LEDA format

394 Views Asked by At

I am using the NetworkX python module to work with graphs and I'm happy with it so far.

However, I tried to write a graph to a file in LEDA format (more information here). The NetworkX documentation does not seem mention any function to do it (I only found how to read and parse LEDA formatted graphs). Is there a function to write graphs in LEDA format that I haven't seen?

1

There are 1 best solutions below

0
On

I have created a code to write graph in leda format :

import networkx as nx
import os
import pandas as pd
df = pd.read_csv(file,header=0,sep="\t")
    G = nx.Graph()
    G = nx.from_pandas_edgelist(df, 'from', 'to')
    path_sub_network_leda=str(file)+ ".gw"
    with open(path_sub_network_leda,"a") as file_graph:
        file_graph.write('LEDA.GRAPH\n')
        file_graph.write('void\n')
        file_graph.write('void\n')
        file_graph.write('-2\n')
        file_graph.write(str(G.order())+str("\n"))
        nodes = list(G)
        nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
        for n in nodes:
            node_row=str("|{") + str(n) + str("}|")+str("\n")
            file_graph.write(node_row)
        file_graph.write(str(G.number_of_edges())+str("\n"))
        for u, v, edgedata in G.edges(data=True):
            d = edgedata.copy()
            edge_row=str(nodenumber[u]) +" " + str(nodenumber[v])+ " "+ str(0)+ str(" |{}|") +str("\n")
            file_graph.write(edge_row)