script in python: Template is not defined
Question: I am using the following Python script:

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    import nibabel
    import os
    
    def collapse_probtrack_results(waytotal_file, matrix_file):
        with open(waytotal_file) as f:
            waytotal = int(f.read())
        data = nibabel.load(matrix_file).get_data()
        collapsed = data.sum(axis=0) / waytotal * 100.
        return collapsed
    
    matrix_template = 'results/{roi}.nii.gz.probtrackx2/matrix_seeds_to_all_targets.nii.gz'
    processed_seed_list = [s.replace('.nii.gz','').replace('label/', '')
        for s in open('/home/salvatore/tirocinio/aal_rois_diff_space/aal.txt').read().split('\n')
        if s]
    N = len(processed_seed_list)
    conn = np.zeros((N, N))
    rois=[]
    idx = 0
    for roi in processed_seed_list:
        matrix_file = template.format(roi=roi)
        seed_directory = os.path.dirname(result)
        roi = os.path.basename(seed_directory).replace('.nii.gz.probtrackx2', '')
        waytotal_file = os.path.join(seed_directory, 'waytotal')
        rois.append(roi)
        try:
            # if this particular seed hasn't finished processing, you can still
            # build the matrix by catching OSErrors that pop up from trying
            # to open the non-existent files
            conn[idx, :] = collapse_probtrack_results(waytotal_file, matrix_file)
        except OSError:
            pass
        idx += 1
    
    # figure plotting
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(conn, interpolation='nearest', )
    cax.set_cmap('hot')
    caxes = cax.get_axes()
    

When I try to run it I get the following error: NameError: name 'template' is
not defined. This refers to line 22 of the script above. Can you please help
me to figure out what is this about?


Answer: There is no variable like `template`, so `template` cannot be used in the
right side of the expression. Try

    
    
        matrix_file = matrix_template.format(roi=roi)
    

instead.

