Search code examples
pythongoogle-sheetsgspread

How do i search for a text in a column and then use that column to print the entire row using gspread & python?


Here's the example of my code.

cell_list = wks.find(input_ID)
print("Text found at R%sC%s" % (cell_list.row, cell_list.col))
get_row = int(("%s" % (cell_list.row)))
print(get_row)
searched_row = wks.row_value(get_row)
print(searched_row)

The error I'm getting...

Text found at R5C5
5
Traceback (most recent call last):
  File "d:/Users/Win81/Desktop/testing.py", line 18, in <module>
    searched_row = wks.row_value(get_row)
AttributeError: 'Worksheet' object has no attribute 'row_value'

I realize the problem is at the get_row. I've searched up online and all the examples are putting in a number in the bracket. However, how do I go about doing this? Thank you for your help!


Solution

  • You have a typo in the line where you are trying to get the row values:

    • Currently: searched_row = wks.row_value(get_row)
    • Should be: searched_row = wks.row_values(get_row)

    (Notice plural row_values ... not singular row_value)

    When I make this correction, your code runs fine on an example that I set up to replicate your problem:

    (BEFORE THE TYPO FIX)
    > python gspread-fix.py
    Text found at R5C5
    5
    Traceback (most recent call last):
      File "gspread-fix.py", line 20, in <module>
        searched_row = wks.row_value(get_row)
    AttributeError: 'Worksheet' object has no attribute 'row_value'
    
    (AFTER THE TYPO FIX)
    >python gspread-fix.py
    Text found at R5C5
    5
    ['y', 'z', '0', '1', '2', '3']
    

    For reference, here's a copy of the complete code with the typo fix and a snapshot of the Google Sheet that I used to test and verify the fix:

    import gspread
    
    gc = gspread.service_account()
    
    # Open a sheet from a spreadsheet in one go
    wks = gc.open("gspread-test").sheet1
    
    input_ID = '2'
    # original
    cell_list = wks.find(input_ID)
    print("Text found at R%sC%s" % (cell_list.row, cell_list.col))
    get_row = int(("%s" % (cell_list.row)))
    print(get_row)
    searched_row = wks.row_values(get_row)
    print(searched_row)
    

    enter image description here

    For further reference, if others are interested in getting started with gspread, I found this quick authentication run-through very helpful: