使用json加载和转储的txt文件中的词典

问题描述 投票:-2回答:1

我想将字典保存在txt文件中,然后需要将该文本文件读取到一个新变量中并进行打印,为此,我需要使用json模块并使用.dump()和.load ()。

到目前为止,这是我的代码,我还是编程的初学者,所以请帮助我,我非常迷失


import json
try:
    file = open("information.txt", "rt")
except:
    print("no file was found")
dict = {
    "a":1,
    "b":2,
    "c":3
}

open('information.txt', 'w')
json.dump(dict, file)
open('information.txt', 'r')
file2 = json.load(file)
print(file2.read())
python json python-3.x python-requests
1个回答
0
投票

阅读:

import json
from pathlib import Path

try:
    data = json.loads(Path('information.txt').read_text())
except FileNotFoundError:
    print("No file was found!")

撰写:

import json
from pathlib import Path

data = {
    "a": 1,
    "b": 2,
    "c": 3
}

data = Path('information.txt').write_text(json.dumps(data, indent=4))

此外,请不要使用dict作为变量名,因为它是Python中的保留关键字。

© www.soinside.com 2019 - 2024. All rights reserved.