I am creating a bot in discord for organizing lists then updates the lists to google sheet via gspread. The lists updated fine, however, if someone removed themselves from the list, the corresponding cell does not get removed, unless a new person replaced them in the list. I think its because of how python deals with list where empty spaces are simply.. nothing therefore gspread just ignores it. Therefore, my question is how do I force gspread to update every cells with an empty string should the list doesn't contains one? Thanks.
# Some codes
import gspread
gc = gspread.service_account(filename = 'a json')
sh = gc.open_by_key("a key")
# My lists
list1 = ["a","b","c"]
list2 = ["d","e","f"]
list_of_lists = [list1, list2]
# Update list into sheet
sh.values_update(
'Sheet1!A1:C2', # fixed cells
params={'valueInputOption': 'RAW'},
body={'values': list_of_lists}
)
# Update with new list
list1.remove("a")
list2.remove("d")
# Rerun list update
sh.values_update(
'Sheet1!A1:C2', # fixed cells
params={'valueInputOption': 'RAW'},
body={'values': list_of_lists}
)
In this answer, a dummy list including the empty values is used. And, the values are put using the method of batch_update
in class gspread.models.Worksheet. In this case, one API call is used.
sh = gc.open_by_key("a key")
sheetName = 'Sheet1' # Please set the sheet name.
worksheet = sh.worksheet(sheetName)
# My lists
list1 = ["a", "b", "c"]
list2 = ["d", "e", "f"]
list_of_lists = [list1, list2]
dummy = [[''] * len(e) for e in list_of_lists]
list1.remove("a")
list2.remove("d")
worksheet.batch_update([{
'range': 'A1:C2',
'values': dummy,
}, {
'range': 'A1:C2',
'values': list_of_lists,
}])
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加