| Reference | Downloads | Github

Is there any way to save exp data after every trial?

I am using code below to save experiment data.


However, due to complex i/o stream, sometimes the Psychopy freezes and lose the whole data of the session.
Is there any way to save data after each trials?

1 Like

I wrote a function for this manually and it worked perfectly for me. However, you have to set up this function once before you start your experiment and change a) the header of the function, b) the header of the file (i.e. the first writerow command), and c) the 2nd writerow command accordingly.

def writeTrialToFile(condition, shapename, rating, rt, shock):
    # check if file and folder already exist
    dir = 'data'
    if not os.path.isdir(dir):
        os.makedirs(dir) #if this fails (e.g. permissions) you will get an error
    fileName = dir + os.path.sep + expName + '_' + expInfo['Subject'].zfill(2) + '.csv' #generate file name with name of the experiment
    # open file
    with open(fileName, 'ab') as saveFile: #'a' = append; 'w' = writing; 'b' = in binary mode
        fileWriter = csv.writer(saveFile, delimiter='\t') #generate fileWriter object
        if os.stat(fileName).st_size == 0: #if file is empty, insert header
            fileWriter.writerow(('expName', 'subject', 'gender', 'safe1', 'threat1', 'safe2', 'threat2', 'block', 'trial', 'condition', 'rating', 'rt', 'shock', 'shapename', 'timestamp'))
        #write trial
        fileWriter.writerow((expName, expInfo['Subject'], expInfo['gender'], expInfo['safe_1'], expInfo['threat_1'], expInfo['safe_2'], expInfo['threat_2'], block, trial, condition, rating, rt, shock, shapename, getTimestamp()))

def getTimestamp(time="", format='%Y-%m-%d %H:%M:%S'): 
    if time=="": return getTimestamp(core.getAbsTime(), format)
    return datetime.datetime.fromtimestamp(time).strftime(format)
1 Like