I have a python script with each time running ,it returns a new value. Then I need to add those values to a google sheet. So every day the outcome of the scripts will be added to a new row. I tried to use “pygsheet” lib but I can not handle the addition to new row for each day. How can I add the data to the last empty row?
There are multiple ways to achieve this using pygsheets. insert_rows can achieve this in a single line.
wks.insert_rows(wks.rows, values=[daily_value], inherit=True) # here wks is the worksheet object
If you dont want to add a new row or want to add value in a non-last row you can use append_table, assuming this is the only data in the sheet. Here you have to make sure your sheet have enough rows to fit new value.
wks.append_table(values=[daily_value])
First, get all values in the spreadsheet. You need to specify include_tailing_empty_rows and include_tailing_empty as False, so that empty rows will not be included in the count
new_row = ['firstname', 'lastname', 'Email', 'Number']
worksheet = gc.open('Sign Up').sheet1
cells = worksheet.get_all_values(include_tailing_empty_rows=False, include_tailing_empty=False, returnas='matrix')
last_row = len(cells)
worksheet = worksheet.insert_rows(last_row, number=1, values= new_row)
insert_rows adds the "new_row" list to the position immediately after "last_row".
You can check out other attributes of worksheet here https://pygsheets.readthedocs.io/en/stable/worksheet.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With