0

I have three list that I'd like to write to .csv file, where each list is written as a column. Example:

x = [0,1,2,3,4]
y = [0,1,4,9,16]
z = [1,1,1,1,1]

The file would then have the structure:

0 0 1
1 1 1
2 4 1
3 9 1
4 16 1

I don't mind if what the delimiter is. Tabs, commas etc is fine.

I've tried something like:

numpy.savetxt('file.csv',zip(x,y,z))

But this just creates a 1D list with alternating values of x, y and z, I thought it would work?

Thanks

1 Answer 1

1

You can do it like below:

import csv

with open('file.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for i, j, k in zip(x, y, z):
        writer.writerow((i, j, k))

Result:

>>> with open('file.csv', 'r') as csvfile:
...     print(csvfile.read())
...
0,0,1
1,1,1
2,4,1
3,9,1
4,16,1
Sign up to request clarification or add additional context in comments.

3 Comments

This is great! Thanks
@RichardHall You're welcome, don't forget to accept it as answer to your question :)
Just did, was waiting for the 10min timer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.