Python 如何将整数写入文件
我需要写信Python 如何将整数写入文件,python,Python,我需要写信 ranks[a], ranks[b], count 到一个文件,每次都在一个新行上 我正在使用: file = open("matrix.txt", "w") for (a, b), count in counts.iteritems(): file.write(ranks[a], ranks[b], count) file.close() 但这是行不通的,而且还会回来 TypeError: function takes exactly 1 argument (3 gi
ranks[a], ranks[b], count
到一个文件,每次都在一个新行上
我正在使用:
file = open("matrix.txt", "w")
for (a, b), count in counts.iteritems():
file.write(ranks[a], ranks[b], count)
file.close()
但这是行不通的,而且还会回来
TypeError: function takes exactly 1 argument (3 given)
正如错误所说,只需要一个arg。尝试:
file.write("%s %s %s" % (ranks[a], ranks[b], count))
哈米什的回答是正确的。但是,当您将内容读回时,您将把它们作为
字符串
而不是整数
来读取。因此,如果您想将它们作为整数或任何其他数据类型读回,那么我建议使用某种对象序列化
,比如pickle
对于
pickle
,您应该阅读官方文档。为方便起见,我粘贴了以下内容的一个片段:
# Load the dictionary back from the pickle file.
import pickle
favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }
听起来您希望在
print
语句上添加一个变体
Python2.x:
print >> file, ranks[a], ranks[b], count
Python3.x:
print(ranks[a], ranks[b], count, file=file)
与上面提出的
file.write
解决方案相比,print
语句的优点是,您不必担心那些讨厌的换行符。更有可能是%d
。也不要忘记'\n'
。这里是文件。write(“%d%d%d\n”%(秩[a],秩[b],计数))
@Julia-将其添加到第一部分:“%s%s\n”@Julia-%s”%一些int将只对其调用str(),它们是等价的。您的输出被解释为write函数的3个参数,如错误所示,只能接受1个参数。您可能希望将参数连接到一个变量中,然后将该变量传递给write函数。
print(ranks[a], ranks[b], count, file=file)