【发布时间】:2012-05-30 20:58:24
【问题描述】:
我正在从图表中生成随机边并打印它们,但每次我尝试将其保存到文本文件时,都会出现TypeError: expected a character buffer object 之类的错误。代码如下:
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)
我需要将 random_edge 的输出保存在文本文件中,最好保存在列中,因为random_edge 的值采用(abcdef, pqrstu) 的形式。我想将两者放在同一行的单独列中,并将下一个值放在同一列中。我知道我可以使用"\n" 将输出转换为换行符,但是当我使用
ff.write(random_edge + "\n")
我收到一个错误TypeError: can only concatenate tuple (not "str") to tuple。
【问题讨论】:
-
您可能希望使用
print(..., file=ff)而不是ff.write(...)。 (我假设您使用的是 Python 3.x。) -
错误信息准确地告诉您您需要知道的内容。
random_edge是一个元组,“\n”是一个字符串。你认为tuple + string的结果是什么?
标签: python text-files