You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GSpread v5.4.0如何在指定文件夹创建电子表格?

在gspread新版本中指定文件夹创建电子表格的替代方法

gspread从v5.3.0版本后移除了create方法的folder_id参数,直接传入该参数会触发TypeError: create() got an unexpected keyword argument 'folder_id'错误,以下是两种可行的替代方案:

方案1:先创建表格再移动到目标文件夹

  1. 先在Drive根目录创建电子表格
  2. 通过Drive API将表格移动到指定文件夹

代码示例:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

credPathRoot = os.path.expanduser('myjsonPath')
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name(credPathRoot, scope)
gc = gspread.authorize(credentials)

spreadSheetTitle = 'NewSpreadsheetDelete'
folderId = '###FolderID###'

# 创建表格(默认存放在Drive根目录)
workbook = gc.create(spreadSheetTitle)

# 获取表格的Drive文件ID
spreadsheet_id = workbook.id

# 获取当前父文件夹(根目录)并替换为目标文件夹
file = gc.drive.files().get(fileId=spreadsheet_id, fields='parents').execute()
previous_parents = ",".join(file.get('parents'))
gc.drive.files().update(
    fileId=spreadsheet_id,
    addParents=folderId,
    removeParents=previous_parents,
    fields='id, parents'
).execute()

注意:需确保服务账号拥有目标文件夹的编辑权限,可将服务账号邮箱添加到文件夹的共享成员列表中并赋予编辑权限。

方案2:直接通过Drive API创建表格到指定文件夹

直接构造包含目标文件夹信息的文件元数据,调用Drive API创建表格,无需额外移动操作,效率更高。

代码示例:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

credPathRoot = os.path.expanduser('myjsonPath')
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name(credPathRoot, scope)
gc = gspread.authorize(credentials)

spreadSheetTitle = 'NewSpreadsheetDelete'
folderId = '###FolderID###'

# 构造表格的Drive文件元数据
file_metadata = {
    'name': spreadSheetTitle,
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [folderId]
}

# 创建表格到指定文件夹
file = gc.drive.files().create(body=file_metadata, fields='id').execute()

# 通过文件ID打开表格
workbook = gc.open_by_key(file['id'])

内容的提问来源于stack exchange,提问作者CoolGuyHasChillDay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:25:32