如何将Smartsheet响应写入文件?

2024-04-26 20:55:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谢谢你的帮助/建议。你知道吗

我已经取了sample.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")

Tags: 文件theimporttokennonejsonaccesssmart
1条回答
网友
1楼 · 发布于 2024-04-26 20:55:52

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

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对象列表所在的目录中。你知道吗

相关问题 更多 >