这是我的询问:
import gspread
from google.oauth2.service_account import Credentials
import csv
# Path to your service account key file
SERVICE_ACCOUNT_FILE = '/Users/xxx/Desktop/projects/importcsv.json'
# Scopes for the API
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
# Authorize the client
credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
client = gspread.authorize(credentials)
# Name of the Google Sheets document
spreadsheet_name = 'test csv import'
# Open or create the Google Sheets document
try:
spreadsheet = client.open(spreadsheet_name)
except gspread.exceptions.SpreadsheetNotFound:
spreadsheet = client.create(spreadsheet_name)
spreadsheet.share('xxxxx', perm_type='user', role='writer')
# Open the first sheet
sheet = spreadsheet.sheet1
# Clear the sheet before writing new data
sheet.clear()
# Path to your local CSV file
csv_file_path = '/Users/xxxxxx/Desktop/projects/test csv import - Sheet1.csv'
# Read the CSV file and upload to Google Sheets
with open(csv_file_path, mode='r') as file:
reader = csv.reader(file)
csv_data = list(reader)
# Convert the list of lists (csv_data) to the format expected by gspread (two-dimensional list)
values = [[cell] for row in csv_data for cell in row]
# Update the sheet with the CSV data starting from cell A1
sheet.update('A1', values)
print(f"CSV data has been uploaded to Google Sheets: {spreadsheet_name}")
问题从第 40 行开始,“sheet.update('A1', value)”,尽管脚本似乎在执行,因为我收到打印“CSV 数据已上传到 Google Sheets”,但我收到此错误消息
DeprecationWarning: The order of arguments in worksheet.update() has changed. Please pass values first and range_name secondor used named arguments (range_name=, values=)
sheet.update('A1', values)
我已经弄清楚了该函数如何读取文件,但没有运气,我也按照错误消息的要求进行了格式化,但这样做给了我另一个错误,它说
TypeError:update() 得到了意外的关键字参数“range”`
通过消除这个并只留下值部分,然后它说
类型错误:update() 获得了参数“值”的多个值`
不确定我的方法在脚本的最后是否完全错误,我认为连接到谷歌表的其他部分、凭据密钥和访问都是正确的,这符合我的要求,但同时我对这个更新位感到恼火完全阻止我。
如有任何建议,我们将不胜感激
谢谢
改变
sheet.update('A1', values)
到
sheet.update(values, 'A1')
或使用关键字:
sheet.update(range_name='A1', values=values)