Wb10
Wb10

Reputation: 89

Python gspread CellNotFound exception error

I want to check whether if a cell value exists in my sheet. If the cell exists, it will return yes and if it doesn't, it will return no.

cell = sheet.find('test')
if cell.value =='test':
    print('Yes')
else:
    print('No')

The above code works for the true segment but does not work if false and it returns an error gspread.exceptions.CellNotFound: test. I tried adding an exception, except gspread.exceptions.CellNotFound: but it still does not work.

Any clue in whats wrong with this code?

Upvotes: 3

Views: 1588

Answers (1)

Tanaike
Tanaike

Reputation: 201388

  • You want to search the cell on a sheet in Spreadsheet using a text.
  • You want to achieve this using gspread with python.
  • You have already been able to get and put values for Spreadsheet with Sheets API.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Pattern 1:

When cell = sheet.find('test') is used, when test cannot find in the work sheet, an error of gspread.exceptions.CellNotFound: test occurs. Although I cannot understand about I tried adding an exception, except gspread.exceptions.CellNotFound: but it still does not work., I think that your approach is correct. So can you test the following script?

Sample script:

try:
    cell = sheet.find('test')
    print('Yes')
except gspread.exceptions.CellNotFound:  # or except gspread.CellNotFound:
    print('No')

Pattern 2:

When cells = sheet.findall('test') is used, when test cannot find in the work sheet, an empty array is returned. In this pattern, this is used.

Sample script:

cells = sheet.findall('test')
if len(cells) > 0:  # or if cells != []:
    print('Yes')
else:
    print('No')

Note:

  • If above scripts didn't work, can you post your whole script? By this, I would like to confirm it. Of course, please remove your personal information.

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 2

Related Questions