NickP NickP - 6 months ago 8
Python Question

Dynamic arguments in python write

I am trying to build a function that dynamically deletes and orders rows based on the column numbers it is passed in. So far I have defined the following:

import csv

def delete(rows_to_keep):
with open('file.csv','r') as source:
rdr= csv.reader( source )
with open('reordered.csv','w') as result:
wtr= csv.writer( result, delimiter=',', lineterminator='\n' )
for r in rdr:
wtr.writerow( ... )

rows_to_keep = [1, 3, 5, 6]

delete()


However, in the above, I would like the ... in the writerow(...) to be replaced by arguments as follows:

... = r[1], r[3], r[5], r[6]


i.e.

wtr.writerow( r[1], r[3], r[5], r[6] )


And have the number of arguments and order change depending what is passed in.

I am not quite sure how I could do this if suddenly the array has 10 values. Any ideas??

Answer

Use rows_to_keep in a loop to build a list with the new sequence of values you want to write out. Then pass that list to writerow(); it doesn't accept an arbitrary number of arguments, so you must call it with a list one way or another. Something like this:

rows_to_keep = [1, 3, 5, 6]
...
for row in rdr:
    newrow = list()
    for n in rows_to_keep:
        newrow.append(row[n])
    wtr.writerow(newrow)

PS. Or use a comprehension if you prefer. Same result (if used correctly).

for row in rdr:
    newrow = [row[n] for n in rows_to_keep]
    wrt.writerow(newrow)
Comments