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

如何修改Python代码保存含缺失presence_id的API返回全部数据?

修改方案:保存所有用户数据(无论presence_id是否存在)

直接移除原代码中过滤presence_id的判断逻辑,并优化presence_id的取值方式,避免字段缺失时触发异常,修改后的代码如下:

# get all of the initial users
initialUsers = requests.get(url, headers=headers)

data = initialUsers.json()

userData = data['data']

# write to a txt file
with open('Users.txt', 'x', encoding='utf-8') as f:
    for i in userData:
        # 用get方法获取presence_id,不存在则返回空字符串(可自定义默认值)
        presence_id = i.get('presence_id', '')
        sheet = (i['username'] + " ", i['first_name'] + " ", i['last_name'] + " ", presence_id)
        f.write(str(sheet) + "\n")

关键修改点说明:

  • 移除了if i.get('presence_id') is not None:判断,确保所有用户数据都会被写入文件。
  • 使用i.get('presence_id', '')替代直接取值:当presence_id字段不存在时,会返回你指定的默认值(这里是空字符串,你可以改成"未设置"、"无"等),避免因字段缺失触发KeyError异常。
  • 如果你不确定username、first_name、last_name这几个字段是否一定存在,也可以用同样的get方式取值,比如i.get('username', ''),进一步提升代码的健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:40:46