1

I have 3 lists of integers in format:

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

I am trying to enter these into a CSV file in the following format, with each item in each list taking a row and each list taking a new column:

1  4  7
2  5  8
3  6  9

Currently my code(below) is able to add the first list into the CSV, although i am having trouble adding the second and third lists in the way i wish.

with open('Test.csv', 'wb') as f:
    for item in a:
        csv.writer(f).writerow([item])

Gives CSV Output:

1
2
3

If i simply use the following code the b list is added to the same column, i require it to be inserted into the second column:

for itemB in b:
        csv.writer(f).writerow([itemB])

Gives CSV Output:

1
2
3
4
5
6

How can i achieve this?

0

2 Answers 2

3

zip(a, b, c) gives you a list of rows: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

with open('Test.csv', 'wb') as f:
    w = csv.writer(f)
    for row in zip(a, b, c):
        w.writerow(row)
Sign up to request clarification or add additional context in comments.

1 Comment

To get closer to the OP's output I think you might have to specify the delimiter.
0

This works:

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

with open('/tmp/test.csv','wb') as out:
    for row in zip(a,b,c):
        csv.writer(out, delimiter=' ').writerow(row)

or even:

with open('/tmp/test.csv','wb') as out:
    csv.writer(out, delimiter=' ').writerows(zip(a,b,c))

Output:

$ cat /tmp/test.csv
1 4 7
2 5 8
3 6 9

1 Comment

For brevity you could replace your last two lines with csv.writer(out, delimiter=' ').writerows(zip(a,b,c))

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.