【发布时间】:2018-05-15 07:36:25
【问题描述】:
我遇到的问题是,每当我尝试读取 json 对象时,都没有设置“数据”变量。我只得到一个空集。下面我有代码和输出。
import json
data = []
def add(name, amt):
data.append({"ticker": name, "amount": amt})
def write():
with open('portfolio.json', 'w') as file:
json.dump(data, file)
def load():
with open('portfolio.json', 'r') as file:
data = json.load(file)
def main():
choice = input("Do you want to add vals? (y/n): ")
if choice == 'y':
add('btc', 43.2)
add('xrp', 256.5)
add('xmr', 655.3)
print(data)
write()
if choice == 'n':
load()
print(data)
main()
输出 1:
Do you want to add vals? (y/n): y
[{'ticker': 'btc', 'amount': 43.2}, {'ticker': 'xrp', 'amount': 256.5}, {'ticker': 'xmr', 'amount': 655.3}]
Press any key to continue . . .
所以现在文件 'portfolio.json' 包含包含所有数据的 json 对象,对吗?所以,现在当我尝试阅读它时,我得到的是:
输出 2:
Do you want to add vals? (y/n): n
[]
Press any key to continue . . .
如您所见,data 变量只是一个空集,它不接收数据。但是,如果我进入 load 函数并打印出 data 变量,我会得到我的值。
【问题讨论】:
标签: python json python-3.x file-io