fun6utzi fun6utzi - 2 years ago 88
Python Question

Python export only parts of list to CSV

Please can you help.
Using Python 2.6.6.

I have list called 'results' like:

# This is remark only: Type for `results`: <type 'list'>
1 86561198961563884 430cf63c640accf1c90ed2a9fe2ccce4
2 86561198160451905 d3fe1c990841552483955dfa81234338
3 86561198114921980 099c88e5c344233a388c0e558d3d88c8
4 86561198160858321 85cf9fa846e0f626c2490d12e9c9919e

Currently writing to file 'myOutput.csv' with code:

import csv
with open("myOutput.csv", "wb") as csvfile:
writer = csv.writer(csvfile)

I want this in csv file: {Thus not the "first column" / rows[0]}

86561198961563884 430cf63c640accf1c90ed2a9fe2ccce4
86561198160451905 d3fe1c990841552483955dfa81234338
86561198114921980 099c88e5c344233a388c0e558d3d88c8
86561198160858321 85cf9fa846e0f626c2490d12e9c9919e

The background and why.
Already made changes to list.

Now need to go to CSV for MySQL import.

Thank you,

Answer Source

Slice off the first item from each row.

writer.writerows([line[1:] for line in results])

[1:] means a slice from the element with index 1, which is the first item, all the way to the end. This forms part of a comprehension that performs this slice for each row, creating a new list which is sent to writer.writerows.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download