psychopy.org | Reference | Downloads | Github

Copy selected rows from old csv to new csv

MacOS
PsychoPy 1.90.3

Hello. I’m trying to copy a selection of rows from a csv created earlier in my experiment to a new csv to be used as a conditions file later in the experiment.

This is the closest I’ve gotten to making it work:

Begin Routine

with open('~/Desktop/olddata.csv', "r") as csvfile, open('~/Desktop/newdata.csv", "w") as csvfile_out :
    reader = csv.reader(csvfile, delimiter = ',')
    writer = csv.writer(csvfile_out, delimiter = ',')
    for row in reader:
        writer.writerow(row[1], row[10], row[19])

Instead of copying over the selected rows, it appears to have copied all of the rows from the columns of those respective numbers (e.g., column 1, column 10, and column 19). I assume it’s just a matter of adjusting the csv function but I haven’t had any luck trying to fix it.

Any help pointing me in the right direction would be greatly appreciated!

Try this:

with open('~/Desktop/olddata.csv', 'r') as csvfile, open('~/Desktop/newdata.csv', 'w') as csvfile_out:
    reader = csv.reader(csvfile, delimiter = ',')
    writer = csv.writer(csvfile_out, delimiter = ',')
    for row in (r for i, r in enumerate(reader) if i in [1,10, 19]):
        writer.writerow(row)

Worked perfectly! Many thanks!