简体   繁体   English

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

[英]dictionary in txt file using json load and dump

I want to save my dictionary inside a txt file then I need to read that text file into a new variable and print it, and in order to that, I need to use the json module and use.dump() and.load().我想将我的字典保存在一个 txt 文件中,然后我需要将该文本文件读入一个新变量并打印它,为此,我需要使用 json 模块和 use.dump() 和 .load() .

This is my code so far, I'm also a beginner in programming so please assist me I'm very much so lost到目前为止,这是我的代码,我也是编程的初学者,所以请帮助我,我非常迷茫


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())

To read:读书:

import json
from pathlib import Path

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

To write:来写:

import json
from pathlib import Path

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

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

Also, please don't use dict as a variable name as it is a reserved keyword in Python.另外,请不要使用dict作为变量名,因为它是 Python 中的保留关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM