【问题标题】:Code Review for Creating .JSON file with Python使用 Python 创建 .JSON 文件的代码审查
【发布时间】:2017-11-15 05:13:13
【问题描述】:

以下代码有问题。
它应该最终创建这个“ages.json”文件(因为最初它在目录中不存在。
然后,每次运行时,它都会增加文件中的年龄),但这并没有发生。

import simplejson as json
import os

# checks if the file exists and if the file is empty
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size != 0:
    old_file = open("./ages.json", "r+")
    # loads the file as python readable
    data = json.loads(old_file.read())
    print("Current age is", data["age"], "-- adding a year.")
    data["age"] = data["age"] + 1
    print("New age is", data["age"])
#if the file is empty or doesn't exist
else:
    old_file = open("./ages.json", "w+")
    data = {"name": "Helio", "age": 88}
    print("No file Found, setting default age to", data["age"])

# starts at the beginning of the file
old_file.seek(0)
# "dumps" data into a json file
old_file.write(json.dumps(data))

【问题讨论】:

  • 不要检查文件是否存在。只需在 try/catch 块中阅读即可。您的代码有竞争条件。您还需要了解如何覆盖文件。
  • There's a site specifically for Code Review ,但是不应该存在损坏的代码。
  • 很抱歉。这实际上是我第一次提出问题,通常我可以弄清楚,但这不是我的代码它实际上来自一个课堂视频,并且在视频上它对教练来说非常有效,因为我什么也没做,很好在 IDLE 中打印出“No File...”。

标签: python json python-3.x simplejson


【解决方案1】:

试试这个

import simplejson as json
import os

if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size !=0:
    old_file = open("./ages.json", "r+")
    data = json.loads(old_file.read())
    print("current age is", data["age"], "Adding User" )
    data["age"] = data["age"] + 1
    print("New Age is ", data["age"])
else:
    old_file = open("./ages.json", "w+")
    data = {"name": "Nick", "age": 26}
    print("No default file Found Setting default age to ", data["age"])
old_file.seek(0)
old_file.write(json.dumps(data))

【讨论】:

    【解决方案2】:

    你的逻辑不太正确。

    我建议先处理不存在,然后再加载文件(因为它必须存在)

    import simplejson as json
    import os
    
    filename = 'ages.json'
    f = None 
    # checks if the file doesn't exists or if the file is empty
    if not os.path.isfile(filename) or os.stat(filename).st_size == 0:
        f = open(filename, "w")
        data = {"name": "Helio", "age": 88}
        print("No file Found, setting default age to", data["age"])
        json.dump(data, f)
    if not f:  # open the file that exists now 
        f = open(filename) 
        data = json.load(f) 
    f.close()  # close the file that was opened in either case 
    
    # Print the data from the file
    print("Current age is", data["age"], "-- adding a year.")
    data["age"] = data["age"] + 1
    print("New age is", data["age"])
    

    【讨论】:

      【解决方案3】:

      重写文件时必须先截断,函数truncate()

      【讨论】:

      • 好的,然后在rw打开
      【解决方案4】:

      基本上要做到这一点还有很长的路要走:

      import json
      
      with open("./ages.json", "a+") as f:  # open the file in append+ mode
          f.seek(0)  # move to the beginning of the file
          # read the file or set the 'default' JSON with default (age - 1) as we'll be updating it
          data = json.loads(f.read() or '{"name": "Helio", "age": 87}')
          data["age"] += 1  # increase the age
          f.seek(0)  # move back to the beginning
          f.truncate()  # truncate the rest
          json.dump(data, f)  # write down the JSON
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2017-01-24
        • 2022-11-04
        • 2021-03-27
        • 1970-01-01
        相关资源
        最近更新 更多