【问题标题】:PYTHON - File I/O with JSON objects [duplicate]PYTHON - 带有 JSON 对象的文件 I/O [重复]
【发布时间】: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


    【解决方案1】:

    您需要在加载函数中添加一个返回语句,并将结果存储在data 变量中,然后再打印。

    例如:

    def load():
      with open(filename, 'r') as file:
          return 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':
        data = load()
        print(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 2016-06-15
      • 2015-11-28
      • 2016-08-06
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多