Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update google sheet with new outcome every time python script runs?

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?

like image 700
lameei Avatar asked Oct 28 '25 20:10

lameei


2 Answers

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])
like image 128
Nithin Avatar answered Oct 31 '25 10:10

Nithin


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

like image 41
Omobolaji Avatar answered Oct 31 '25 10:10

Omobolaji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!