简体   繁体   中英

How do I write data from python lists with various lengths of tuples inside to a file?

I have data coming from a function giving a tuple of xy position of a circle, and then a single entry for the radius of a circle. When I print the output of the function it gives me the output below, where the data is float:

((308.5, 221.0), 7.861134052276611)

How can I write this data to a file in a tab-delimited format, for example:

x1, "\t", y1, "\t", r, "\n"

If it's useful to you, the function I am working with is cv2.minEnclosingCircle(contour). I want to save my circle tracking data in a text file so that I can analyze it later.

(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)

You can then write a function for saving data to a file:

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()

If you use this function a lot, you might want to consider out the open-close-file code outside this function.

x = ((308.5, 221.0), 7.861134052276611)

print '{0[0]}\t{0[1]}\t{1}'.format(*x)

result

308.5   221.0   7.86113405228

Try this

fileName.write("%f\t%f\t%f\n"%(tupleName[0][0],tupleName[0][1],tupleName[1]))

where tupleName contains the output of the function and fileName is your file object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM