Reputation: 205
I am generating random edges from a graph and printing them, but every time I try to save it to a text file, I end up with errors like TypeError: expected a character buffer object
. The code is below:
import re
import md5
import pickle
import networkx as nx
import itertools
from random import choice
ff=open("testfile.txt","r+")
G=nx.read_gpickle("authorgraph_new.gpickle")
for nodes in G:
random_edge=choice(G.edges())
ff=open("testfile.txt","a")
ff.write(random_edge)
I need to save the outputs of random_edge in a text file preferably in columns, as the value of random_edge
is in the form (abcdef, pqrstu)
. I want to put the two in separate column in the same line and the next value in the same columns. I know I can use the "\n"
to get the outputs to newline but when I used
ff.write(random_edge + "\n")
I get an error TypeError: can only concatenate tuple (not "str") to tuple
.
Upvotes: 1
Views: 836
Reputation: 2680
Joel's comment is correct: you're concatenating your result (a tuple) with the newline character, a string. Python doesn't like mixing datatypes that way. If you're writing more complex structured data, then in the future you may want to look into python's csv module as well.
Upvotes: 0
Reputation: 758
In that case you may have a try to do it in 2 lines like:
for nodes in G:
ff.write(random_egde)
ff.write('\n')
hope this would work for your case.
here first line writes your data while the second line adds a new line to the data.
Upvotes: 2