user1028861
user1028861

Reputation:

Python loop to write across columns in CSV

I'm trying to write a csv as follows: data[0][0] should be in row 1 column A, data[0][1] should be in row 1 column B, data[1][0] should be in row 2 column A, data[1][1] should be in row 2 column B and so on.

If I use something inefficient like the following code, I can write to the csv as intended.

                for i in range(0, len(data)-lg):
                    writer.writerow([data[i][0], data[i][1], data[i][2],...])

I really need something like the following code. But, this code writes everything in Column A. How can I modify it to accomplish my objective? Thanks.

            for i in range(0, len(data)-lg):
                for j in range(0, lg+6):
                    writer.writerow([data[i][j]])

Upvotes: 1

Views: 3573

Answers (3)

Joe Holloway
Joe Holloway

Reputation: 28948

I think the idiomatic way to do this would be as such (not fully understanding your lg variable):

num_cols = lg + 6
for row in data:
    writer.writerow(row[:num_cols])

If you weren't doing any processing on the rows in the loop, you could do it even more concisely:

writer.writerows(data)

Edit 1 Updated based on comment explaining lg variable

Upvotes: 3

RedBaron
RedBaron

Reputation: 4755

writerow() takes a row (sequence of strings or numbers) as input. Your second code passes only one element to writerow() so the element is written in separate row (i.e. each element in column A). In your first example you do the right thing by passing the entire collection of data row to writerow() so it works. As Dan D. has suggested a more pythonic way is

for x in data:
    writer.writerow(x)

Upvotes: 0

Dan D.
Dan D.

Reputation: 74645

why not?

for row in data:
    writer.writerow(row)

Upvotes: 2

Related Questions