Search code examples
pythonxlrd

XLRD splitting comma separated values of a cell


I am using XLRD library to read a particular cell of an excel sheet. This cell might or might not have multiple comma separated values.

comma separated values in a cell

Please find below my code snippet

from xlrd import open_workbook
from argparse import ArgumentParser as parser

parse = parser()
parse.add_argument('-p', '--path', action='store', dest='path', help='mention the excel sheet path')
args = parse.parse_args()

excelList = []

book = open_workbook(args.path)
dep_cms = book.sheet_by_index(1)
for row_index in range(1, dep_cms.nrows):
    excelList.append(dep_cms.cell(row_index, 8).value)

print(excelList)

for name in excelList:
    print('Dependent CMS is {}'.format(name))

It is printing output like this...

['187013, 187014, 187015']
Dependent CMS is 187013, 187014, 187015

It is treating comma seperated values as a single string.

The ideal output must be like below

['187013', '187014', '187015']
Dependent CMS is 187013
Dependent CMS is 187014
Dependent CMS is 187015

How to split them into CS values? I know we can use split to split the string. But how to use it in this context?

Regards


PS:

Based on suggestion in comments section I have tried split

The result was like this

[['187013', ' 187014']]
Dependent CMS is ['187013', ' 187014']

If I use space instead of comma as delimiter in split, the result is as follows

[['187013,', '187014']]
Thy name is ['187013,', '187014']

It is creating an array inside an array which is not what I want.

Based on suggestion of an answer, the following snippet has worked.

excelList.extend([x.strip() for x in dep_cms.cell(row_index, 8).value.split(',')])

Solution

  • Try:

    excelList = []
    for row_index in range(1, dep_cms.nrows):    
        excelList.extend([x.strip() for x in dep_cms.cell(row_index, 8).value.split(',')])