2

Q1.
enter image description here

I want to get output as:

[Randy, Shaw]

Output Looks like

['Randy', 'None', 'None', 'Shaw', 'None', 'None']

But it is not removing 'None' values.
Here is my code..

from openpyxl import load_workbook
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
print(workbook.get_sheet_names())

sheet=workbook.get_sheet_by_name('marks')

iterheaders = iter(sheet[1])
headers = [str(cell.value) for cell in iterheaders if cell is not None and cell != '']

Keyword_list = list(filter(None, headers))

I even tried the following but it didn't work either:

Keyword_list = [i for i in headers if (None) != len(i)]

Q2. In the same code what if I want to get the sheet by its index rather than by its name in openpyxl. How do I do that?

Analyst
  • 117
  • 3
  • 12
  • 3
    Because that is the *string* `"None"` not the singleton, NoneType object `None` – juanpa.arrivillaga Jul 07 '17 at 16:33
  • 2
    Possible duplicate of [Remove all occurrences of a value from a list?](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – yabk Jul 07 '17 at 16:45

2 Answers2

2

You can filter like so:

s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']

s = [i for i in s if i != "None"]

Keep in mind that in your list you have the string "None", not the object None

For Q2:

workbook = load_workbook('C:/Users/Desktop/test.xlsx')

sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

Your none values are not literal None type values. Their strings. Therefore, you need to test them against strings. eg:

>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>
Christian Dean
  • 22,138
  • 7
  • 54
  • 87