graphnetworkxgraphml

Write multiple iteration of a networkx graph into .graphml format


I created a graph using the following code where I am getting number of nodes and probability as input from the user.

def my_erdos_renyi():
    erdos_renyi_nodes = int(input("Please enter the number of nodes"))
    erdos_renyi_probability = float(input("Please enter the value of probability"))
    G_erdos_renyi = nx.erdos_renyi_graph(erdos_renyi_nodes, erdos_renyi_probability)
    nx.draw(G_erdos_renyi, with_labels=True)
    plt.axis('on')
    plt.show()
my_erdos_renyi()

Later, I am writing this graph using

nx.write_graphml(G_erdos_renyi, "my_erdos_renyi.graphml")

Now, I want to generate and write 100 iterations of this random graph. So I will run the code 100 times in for loop but how to write the logic to store graph with names such as "my_erdos_renyi_1.graphml",

"my_erdos_renyi_2.graphml"

and so on till "my_erdos_renyi_100.graphml"


Solution

  • You can do something like this:

    for i in range(100):
        nx.write_graphml(G_erdos_renyi, f"my_erdos_renyi_{i+1}.graphml")