Search code examples
pythonimport-from-excel

Excel and lists with Python


I am treating Excel sheets using Python. I wrote this :

import xlrd
wb=xlrd.open_workbook('C:\\Inputs_UNF_newForm.xlsx')
s=wb.sheet_by_name('Chemical treatments')

def getOutputs(s):
    for row_index in range(28):
        v = s.cell_value(row_index, 1)
        if s.cell_value(row_index, 1) != "" :
            print ('"'+v +'"'+","),

getOutputs(s)

It works just fine. (Well, except that there is still a coma after the last word..) The thing is, I need to create a list of the result of the getOuputs fonction, ie. a list of the cells I read.

I did this:

OutputList=[getOutputs(s)]
print OutputList[1]

But it didn't work. What am I missing? (The extra coma?)


Solution

  • The problem is that you are just printing the values instead of returning them. Here I use an originally empty list keep and append the values to the keep list, then return that list to the caller.

    def getOutputs(s):
        keep = []
        for row_index in range(28):
            v = s.cell_value(row_index, 1)
            if v != "" :
                keep.append(v)
        return keep
    

    On a side note, an easy way to deal with printing the values without the trailing comma would then be `print(",".join(OutputList)).