【发布时间】:2021-06-07 10:22:43
【问题描述】:
我想在我的文本文件更新后通过重新打开文本文件来重新加载我的 JSON。
import json
with open('np.txt') as np:
np_data = np.read()
np_list=json.loads(np_data)
def reopen_file():
print("reloading")
with open('np.txt') as np:
np_data = np.read()
np_list=json.loads(np_data)
y=1
while(y==1):
#np.flush()
#reopen_file()
x=input("input: ")
print("your input is" +x)
if(int(x)==1):
print(np_list)
y=input("continue?: ")
reopen_file()
print(np_list)
我在输入“y”的值之前更新了文本文件(继续?),但输出保持不变。 (我正在手动编辑文件)
np.txt:
{"a":"1",
"b":"2",
"c":"3",
"d":"4",
"e":"5",
"f":"6",
"g":"7",
"h":"8",
"i":"9"}
【问题讨论】:
-
为什么文件会改变?你没有在任何地方编辑它。此外,没有代码或终端输出的图像! >:(
-
@jemand771 我正在手动编辑文件,而不是在代码中
-
@jemand771 您没有更新实际的
np_list,只需将其返回并设置在循环中即可。 -
请查看one
-
题外话:您可以使用
json.load()一步读取JSON 文件,而不是您当前正在执行的两个步骤(即file.read()后跟json.loads())。