写入JSON会产生TypeError:dump()至少接受2个参数(给定1个) [英] Writing to JSON produces TypeError: dump() takes at least 2 arguments (1 given)

查看:94
本文介绍了写入JSON会产生TypeError:dump()至少接受2个参数(给定1个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载json文件.更新并写回.这是我的尝试,但出现错误:

I am trying to load in a json file. Update it and write it back. Here is my attempt at it but I am getting an error:

TypeError:dump()至少接受2个参数(给定1个参数)

TypeError: dump() takes at least 2 arguments (1 given)

with open('employees.json') as data_file:
    employees = json.load(data_file)
    data_file.close

employees['employees'].append({
    "id": "2",
    "name": "Rob Croft",
    "key": "0003837852"})

with open('employees.json', 'w') as data_file:
    json.dump(employees)
    data_file.close

推荐答案

您忘记了传递文件对象:

You forgot to pass in the file object:

json.dump(employees, data_file)

由于使用with语句将文件对象用作上下文管理器,因此不需要手动关闭文件.而且完全 只是使用data_file.close是多余的,因为您甚至没有调用 file.close()方法.

Since you are using the file object as a context manager with the with statement, you do not need to manually close the file. And using just data_file.close is entirely redundant since you are not even calling the file.close() method.

这篇关于写入JSON会产生TypeError:dump()至少接受2个参数(给定1个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆