ai didi

python - JSON Python 读取/写入 json 文件问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:30 24 4
gpt4 key购买 nike

代码:

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
json.dump(letters, f_obj)


with open(filename) as f_obj:
numbers = json.load(f_obj)
letters = json.load(f_obj)

print(numbers)
print(letters)

我希望能够读取已添加到 json 文件中的多个列表,并将它们设置为单独的列表,以便稍后使用。

我不介意在 json 文件中的每个列表之间添加一个新行,然后以行格式读取它。

最佳答案

为什么不将它们存储在全局字典中?

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

val={'numbers': numbers, 'letters':letters}

with open(filename, 'w') as f_obj:
json.dump(val, f_obj)


with open(filename) as f_obj:
val = json.load(f_obj)
numbers = val['numbers']
letters = val['letters']

print(numbers)
print(letters)

关于python - JSON Python 读取/写入 json 文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46675218/

24 4 0
文章推荐: c - UDP 客户端未收到 UDP 服务器消息
文章推荐: python - 当只有一个窗口应该存在时,Tkinter 在使用多处理选择文件时打开多个 GUI 窗口
文章推荐: node.js - 如何在 javascript 中使用带有双重回调的 setTimeout
文章推荐: html - super 基本的 HTML/CSS 格式化
太空宇宙
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com