[英]dictionary in txt file using json load and dump
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.