【问题标题】:How do I save outputs of a variable in a loop to a text file in python in columns?如何将循环中变量的输出保存到python中的文本文件的列中?
【发布时间】: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


【解决方案1】:

在这种情况下,您可以尝试分两行执行,例如:

for nodes in G:
    ff.write(random_egde)
    ff.write('\n')

希望这对您的情况有用。
这里第一行写入您的数据,而第二行向数据添加新行。

【讨论】:

    【解决方案2】:

    Joel 的评论是正确的:您将结果(元组)与换行符(一个字符串)连接起来。 Python 不喜欢以这种方式混合数据类型。如果您正在编写更复杂的结构化数据,那么将来您可能还想研究一下 python 的 csv 模块。

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2010-12-13
      相关资源
      最近更新 更多