[英]How do I write data from python lists with various lengths of tuples inside to a file?
我的數據來自一個函數,該函數給出圓的xy位置元組,然后為圓的半徑輸入一個條目。 當我print
函數的輸出時,它給我下面的輸出,其中數據是浮動的:
((308.5, 221.0), 7.861134052276611)
如何將這些數據以制表符分隔的格式寫入文件,例如:
x1, "\t", y1, "\t", r, "\n"
如果對您有用,我正在使用的函數是cv2.minEnclosingCircle(contour)。 我想將自己的圈子跟蹤數據保存在一個文本文件中,以便以后進行分析。
(x, y), r = ((308.5, 221.0), 7.861134052276611)
line = "{0}\t{1}\t{2}".format(x, y, r)
file_ = open("some.txt", "w")
file_.write(line)
然后,您可以編寫一個將數據保存到文件的功能:
def save(data, filename):
"""
Here data is a tuple with the form: ((x, y), r)
"""
(x, y), r = ((308.5, 221.0), 7.861134052276611)
line = "{0}\t{1}\t{2}".format(x, y, r)
# Open the file with 'w+' mode in order to add the new lines
# at the end.
file_ = open(filename, "w+")
file_.write(line)
file_.close()
如果您經常使用此功能,則可能需要考慮此功能之外的打開-關閉文件代碼。
x = ((308.5, 221.0), 7.861134052276611)
print '{0[0]}\t{0[1]}\t{1}'.format(*x)
結果
308.5 221.0 7.86113405228
嘗試這個
fileName.write("%f\t%f\t%f\n"%(tupleName[0][0],tupleName[0][1],tupleName[1]))
其中tupleName
包含函數的輸出,而fileName
是您的文件對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.