def cell_remover(contents, key):
    """This function will remove the cells that contain a specific key
    and ensure that the last cell has the correct comma at the end."""
    lines = contents.split('\n')
    line_list = []
    for index in range(len(lines)):
        if key in lines[index]:
            line_list.append(index)
    for element in line_list:
        old_cell_text = ''
        element_current = element
        for lines_before in reversed(lines[:element]):
            element_current += -1
            a = 0
            old_cell_text = lines_before + '\n' + old_cell_text
            if lines_before == '  {':
                a = 1
                for lines_after in lines[element:]:
                    if '  },' in lines_after:
                        old_cell_text = old_cell_text + '  },\n'
                        break
                    elif '  }' in lines_after:
                        old_cell_text = old_cell_text + '  }\n'
                        break
                    else:
                        old_cell_text = old_cell_text + lines_after + '\n'
            if a == 1:
                break
        contents = contents.replace(old_cell_text, '')
    lines = contents.split('\n')
    kernel_spec_index = None
    for index in range(len(lines)):
        if '"kernelspec": {' in lines[index]:
            kernel_spec_index = index
            break
    kernel_spec_text = ''
    if kernel_spec_index is not None:
        for line in reversed(lines[:kernel_spec_index]):
            if line == '  }':
                break
            elif line == '  },':
                contents = contents.replace('  },\n' + kernel_spec_text, 
                    '  }\n' + kernel_spec_text)
                break
            else:
                kernel_spec_text = line + '\n' + kernel_spec_text
    return contents
