简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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