1

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.

2
  • You probably want to use print(..., file=ff) instead of ff.write(...). (I'm assuming you are using Python 3.x.) Commented May 30, 2012 at 9:02
  • 3
    The error message tells you exactly what you need to know. random_edge is a tuple, "\n" is a string. What do you expect the result of tuple + string to be? Commented May 30, 2012 at 9:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.