'How do I extract data as strings from Google Sheets column?

I'm in the process of learning the Google Sheets API with Python. I'm trying to extract data from a column in the spreadsheet, but it extracts it as a list of lists. For example, if the list contains the following names in Column A of the spreadsheet.

Alexandra
Andrew
Anna
Becky
Benjamin

I started off by importing the gspread library and initial variables, then grabbed the entire column, stored it into a variable, and printed.

import gspread

sa = gspread.service_account()
sh = sa.open("gSheets-Python")
wks = sh.worksheet("Class Data")

sheetsColA = wks.get('A2:A')
print(sheetsCol)

This yielded the following console output.

[['Alexandra'], ['Andrew'], ['Anna'], ['Becky'], ['Benjamin']]

Suppose that I want to store the 3rd entry from this list ("Anna"), so I ran print(sheetsCol[2]), which yielded ['Anna']. In another example, I noticed that they ran print(wks.acell(A4).value) which yielded Anna, without the brackets.

Attempting to do the same on the get function, I get an error. I ran print(sheetsCol[2].value), hoping to get Anna, but instead got the following error.

Traceback (most recent call last):
  File "script.py", line 24, in <module>
    print("sheetsCol[2] = ", sheetsCol[2].value, "\n")
AttributeError: 'list' object has no attribute 'value'

How do I get Anna as just a string in a variable, instead of ['Anna']? Does it need to be in the ['Anna'] format if I want to use the code to paste it back into the sheet in a different location? Like if I want to move or copy Anna to the D4 cell.

The long-term goal is to grab data from a column, and process them one-by-one for web scraping with BeautifulSoup4, then paste the web-scraped results in another column in the sheet. The web scraping is for another discussion, but is this the correct overall approach?



Solution 1:[1]

Solutions:

  1. Just use starred expression to unpack list print(*["txt"])
  2. Use for loop to run through values.
  3. Use list indexes to get value var = lst[0]

The error occurs because: sheetsCol[2] is a list, I may suppose that it is the list of wks.acell objects, therefore u can go through it and acquire all values. Example:

for i in sheetsCol[n]:
    print(i.value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1