简体   繁体   中英

How can I append row values to a Google sheet using a list, array or loop in Python?

I have a Python script which is called by Bash script with arguments (parameters) using sys. I can successfully append these parameters to a Google Sheet when they are included as individual values in the worksheet.append.rows command. If the number of parameters in the call do not match the number of values in the append command, it fails.

It's easy to find the length of the sys.argv array and print the values in a loop. How can I provide the worksheet.append.rows command with a similarly dynamic list of the arguments passed by the Bash script, removing the need to hard code the number of values?

Posts on this topic seem to me to be rather complicated. I'm hoping that there is a simple solution out there.

This is my first question and I am new to Python!

import sys
import gspread

for i in range(len(sys.argv)):
    print(sys.argv[i])

gc = gspread.service_account(filename='gsa.json')

worksheet = gc.open("gfx-garden-meta").sheet1

# this is where I am stuck for a flexible way to supply the right number of values to the append command:

worksheet.append_rows(values=[[(sys.argv[1]), (sys.argv[2]), (sys.argv[3]), (sys.argv[4]), (sys.argv[5]), (sys.argv[6])]])

#

exit()

Below will create a list of lists, where each inner list contains a single element, which is an argument passed by the Bash script. Then you can pass that list to append_rows function

values = [[arg] for arg in sys.argv[1:]]
worksheet.append_rows(values)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM