[英]How to write integers to a file
我需要寫
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)
正如錯誤所說, file.write
只需要一個arg。 嘗試:
file.write("%s %s %s" % (ranks[a], ranks[b], count))
哈米什的回答是正確的。 但是當你要閱讀內容時,你會把它們看作strings
而不是integers
。 因此,如果您想要將它們作為整數或任何其他dataType讀取,那么我建議使用某種類型的object serialization
如pickle
。
為了pickle
您的數據,您應該閱讀官方文檔中的此頁面 。 為了您的方便,我從這里粘貼一個片段:
# 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" }
聽起來你想要在print
語句中有變化。
Python 2.x:
print >> file, ranks[a], ranks[b], count
Python 3.x:
print(ranks[a], ranks[b], count, file=file)
print
語句優於上面提出的file.write
解決方案的優點是你不必擔心那些討厭的新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.