gpt4 book ai didi

python - 如何将 Smartsheet 响应写入文件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:33 26 4
gpt4 key购买 nike

我正在尝试编写一些基本代码来检索工作区列表并将响应写入文件。我认为这可以转储到 JSON 文件中?

感谢您的帮助/建议。

我已经获取了示例 .py 文件并将其重新设计为如下所示 -

# Install the smartsheet sdk with the command: pip install smartsheet-python-sdk
import smartsheet
import logging
import os.path
import json

# TODO: Set your API access token here, or leave as None and set as environment variable "SMARTSHEET_ACCESS_TOKEN"
access_token = None

print("Starting ...")

# Initialize client
smart = smartsheet.Smartsheet(access_token)
# Make sure we don't miss any error
smart.errors_as_exceptions(True)

# Log all calls
logging.basicConfig(filename='rwsheet.log', level=logging.INFO)

response = smart.Workspaces.list_workspaces(include_all=True)
workspaces = response.data


with open('data.json', 'w') as outfile:
json.dump(workspaces, outfile)


print("Done")

最佳答案

我不确定您面临什么问题,但我认为您可能会遇到 json.dump(workspaces, outfile) 的问题。行作为该结果 workspaces变量是 list您需要迭代才能获取数据。使用该变量只会打印出指针,如下所示: [<smartsheet.models.workspace.Workspace object at 0x10382a4e0>]
要解决此问题,您需要循环变量的结果并将它们打印到文件中。我找到了这篇文章here关于将输出打印到文件。答案给出了三种方法,我能够让它们中的每一种都使用循环迭代结果。
一个例子:

import smartsheet

smar_client = smartsheet.Smartsheet(<ACCESS_TOKEN>)

response = smar_client.Workspaces.list_workspaces(include_all=True)
workspaces = response.data

with open('workspaces.json', 'w') as f:
for workspace in workspaces:
print(workspace, file=f)

运行这个给了我一个 workspaces.json文件位于我运行脚本的同一目录中,列表为 workspace对象。

关于python - 如何将 Smartsheet 响应写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com