[英]How to write integers to a file
I need to write 我需要写
ranks[a], ranks[b], count
to a file, each time on a new line 到一个文件,每次都在新的一行
I am using: 我在用:
file = open("matrix.txt", "w")
for (a, b), count in counts.iteritems():
file.write(ranks[a], ranks[b], count)
file.close()
but this is not working and returns 但这不起作用并返回
TypeError: function takes exactly 1 argument (3 given)
As the error says, file.write
only takes one arg. 正如错误所说,
file.write
只需要一个arg。 Try: 尝试:
file.write("%s %s %s" % (ranks[a], ranks[b], count))
Hamish's answer is correct. 哈米什的回答是正确的。 But when you would be reading the contents back you would be reading them as
strings
and not as integers
. 但是当你要阅读内容时,你会把它们看作
strings
而不是integers
。 So if you'd want to read them back as integers or as any other dataType, then I would suggest using some kind of object serialization
like pickle
. 因此,如果您想要将它们作为整数或任何其他dataType读取,那么我建议使用某种类型的
object serialization
如pickle
。
For pickle
-ing your data, you should read this page in the official documentation. 为了
pickle
您的数据,您应该阅读官方文档中的此页面 。 For your convenience, I am pasting a snippet from here : 为了您的方便,我从这里粘贴一个片段:
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )
# 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" }
It sounds like you want a variation on the print
statement. 听起来你想要在
print
语句中有变化。
Python 2.x: Python 2.x:
print >> file, ranks[a], ranks[b], count
Python 3.x: Python 3.x:
print(ranks[a], ranks[b], count, file=file)
The advantage of the print
statement over the file.write
solution proposed above is that you don't have to worry about those pesky newlines. print
语句优于上面提出的file.write
解决方案的优点是你不必担心那些讨厌的新行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.