Bob
Bob

Reputation: 453

Save a list of tuple to csv file in python

I have a list of tuple which looks like this:

data = [(1633098324445950024, 139.55, 15, [14, 37, 41]),
        (1633098324445958000, 139.55, 100, [14, 41]),
        (1633098324445958498, 139.55, 60, [14, 37, 41]),
        (1633098324446013523, 139.55, 52, [14, 37, 41]),
        (1633098324472392943, 139.555, 100),
        (1633098324478972256, 139.555, 100)]

I am trying to save it in a csv file with:

def save_csv(data, path, filename):
    with open(os.path.join(path, str(filename) + '_data.csv'), "w") as outfile:
        outfile.write("\n".join(f"{r[0]},{r[1]},{r[2]},{r[3]}" for r in data))

save_csv(data, path, filename)

I am getting the IndexError:

    outfile.write("\n".join(f"{r[0]},{r[1]},{r[2]},{r[3]}" for r in data))

IndexError: tuple index out of range

I would like the result looks like this:

enter image description here

Upvotes: 1

Views: 4154

Answers (2)

tdelaney
tdelaney

Reputation: 77347

You have a variable number of columns - r[3] won't always exist. This is a great use case for pandas which will add defaults as needed. I bit more subtle, but pandas will also quote the final column so that that a later reader will know to ignore its embedded commas.

import pandas as pd

data = [(1633098324445950024, 139.55, 15, [14, 37, 41]),
        (1633098324445958000, 139.55, 100, [14, 41]),
        (1633098324445958498, 139.55, 60, [14, 37, 41]),
        (1633098324446013523, 139.55, 52, [14, 37, 41]),
        (1633098324472392943, 139.555, 100),
        (1633098324478972256, 139.555, 100)]

pd.DataFrame(data).to_csv("test.csv")

Upvotes: 3

Ilya Kharlamov
Ilya Kharlamov

Reputation: 3932

import csv

data = [(1633098324445950024, 139.55, 15, [14, 37, 41]),
        (1633098324445958000, 139.55, 100, [14, 41]),
        (1633098324445958498, 139.55, 60, [14, 37, 41]),
        (1633098324446013523, 139.55, 52, [14, 37, 41]),
        (1633098324472392943, 139.555, 100),
        (1633098324478972256, 139.555, 100)]

with open("csv.csv", "w") as f:
    csv_writer = csv.writer(f)
    for mytuple in data:
        csv_writer.writerow(mytuple)

Upvotes: 5

Related Questions