Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Supported by

[open] Use .csv in lieu of loop "spreadsheet"

edited April 2014 in OpenSesame


I've seen several responses which do "nearly" what I want so please excuse me for not being able to work it out for myself:

I'd like to use a .csv (or other text file) as a "drop-in replacement" for the variable data in a "loop" (so that I can edit some complex materials externally). Following this discussion it seems easy to read stuff in and transfer it to experimental variables, but if I understand the example correctly it had six items hard-coded in?

What I'd like to do is generalise the solution into a loop, so that I can read in an arbitrary number of items into "setcycle" variables without having to write repetitive and error-prone code. And for some reason, a sensible solution is eluding me... Any pointers hugely appreciated!



  • edited May 2014

    I had to do something not too dissimilar recently, which I've detailed here.

    For your case, I would try adjusting the code at the bottom of the page to something along the lines of this (although I haven't tested this in OpenSesame yet):

    import csv
    # Read the csv file into a list, with one entry per row
    with open('stimuli_file.csv', 'rb') as stimfile:
        reader = csv.reader(stimfile, delimiter=',')
        contents = [row for row in reader]
    # Make a list of dict items, with the column names from the 
    # top of the csv file as keys, and the subsequent columns
    # as values.
    col_names = contents[0]
    stimuli = [dict(zip(col_names, row)) for row in contents[1:]]
    # Transform these stimuli to OpenSesame variables.
    # To illustrate, imagine the first two variables are "probe" and "condition"
    for i in range(len(stimuli)):
        trial = stimuli[i]
        exp.set("probe_%i" % i, trial["probe"])
        exp.set("condition_%i" % i, trial["condition"])
        exp.set("other_variable_%i" % i, trial["other_variable"])
    # ...sets [probe_0] to the first row in the "probe" column of your csv, etc, up
    # to [probe_N], where N is the number of trials minus 1.

    You can then use the example loop object in the link to use these loaded variables.

    Edit: Be aware that any numerical variables will be saved as strings using this method. OpenSesame might deal with this gracefully and you won't need to worry, but otherwise you may need to use the python int() function:

    <br />for i in range(len(stimuli)):
        trial = stimuli[i]
        exp.set("numeric_variable_%" % i, int(trial["numeric_variable"]))

    Again, without testing this, I just don't know.

  • edited 1:32AM

    Hi, this looks great, thanks Eoin! I'll have a play and post here when done.


Sign In or Register to comment.