4

I'm making a conditional statement in openpyxl Python to check if a cell is empty. Here's my code:

newlist = []
looprow = 1
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()        
for i in range(0, lengthofdict):
    prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
    if prevsymbol == "None":
        pass
    else:
        newstocks.append(prevsymbol)
        looprow += 1
    #print (prevsymbol)
print(newlist)

I tried if prevsymbol == "": and if prevsymbol == null: to no avail.

drevicko
  • 14,382
  • 15
  • 75
  • 97
Newboy11
  • 2,778
  • 5
  • 26
  • 40

2 Answers2

3

You compare prevsymbol with str "None", not None object. Try

if prevsymbol == None:

Also here

prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value

you use looprow as row index. And you increment looprow only if cell.value is not empty. Here

newstocks.append(prevsymbol)

you use newstocks instead of newlist. Try this code

newlist = []
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()        
for i in range(0, lengthofdict):
    prevsymbol = readex.cell(row = i+1,column=getnewhighcolumn).value
    if prevsymbol is not None:
        newlist.append(prevsymbol)
print(newlist)
kvorobiev
  • 5,012
  • 4
  • 29
  • 35
  • @Newboy11 Or add line `print(prevsymbol )` before `if` condition and post results – kvorobiev Jul 17 '15 at 12:45
  • Here's some of the result: one, None, None, None, None, None, '100', '200', '67', '300'. my input data is in excel in a column mixed with not empty and empty cells. I just want to get the non empty cells – Newboy11 Jul 17 '15 at 13:07
  • @Newboy11 If all works fine you could check my answer as right answer) – kvorobiev Jul 17 '15 at 15:02
0

Take the quotes away from the None.

if prevsymbol is None:

This is the python equivalent of checking if something is equal to null.

atlspin
  • 76
  • 8
  • @Newboy11 I can't find anything in the openpyxl documentation that tells you what it returns for an empty cell. Is there any way you can tell me what happens if you print `prevsymbol` on an empty cell? – atlspin Jul 17 '15 at 12:52