【问题标题】:JSON File I/O : Extra Data ErrorJSON 文件 I/O:额外数据错误
【发布时间】:2017-12-20 18:12:24
【问题描述】:

我目前正在学习 Python。对于一个小项目,我正在编写一个脚本来转储和加载从网络中提取的 JSON。每次拉取数据后需要不断更新文件,同样的,我写了如下代码。

    with open(os.path.join(d,fname),'a+') as f:
        try:
            f.seek(0)
            t = json.load(f)
            for i in t:
                tmp[i]=t[i]
        except Exception as e:
            print(e,"New File ",fname," is created in ",d)
        f.truncate()
        json.dump(tmp,f)

自从该程序第一次运行以来,我已经放置了一个 try-catch 块,该文件将没有写入任何数据。

当我运行脚本时,它按预期工作,但是当我第四次运行相同的脚本时,它给出了 EXTRA DATA 异常。

额外数据:第 1 行第 29245 列(char 29244)新文件 TSLA_dann 于 2017 年 12 月 20 日创建

我不确定另一个字典是如何写入文件中的。请指导我。

【问题讨论】:

    标签: python json file io


    【解决方案1】:

    用这样的代码编写另一个 json 几乎是不可能的。你的代码不好。你混合太多尝试打开,寻找和截断,错误的文件模式选择可能。我会教你一点点变得更好:

    1. try 应仅涵盖可能引发错误的内容。
    2. Seek 不需要总是 seek(0) 是在打开之后。
    3. open(x, 'a+) 表示追加到我认为的末尾(我可能是错误的原因)。
    4. 使用空格。
    5. 耐心点。

    问题可能是“a+”模式,但清理代码并不重要:)

    相信我,我编写了 250 000 行程序没有问题。

    干净的代码作为一个很好的例子应该可以工作(我没有经过测试 - 如果一个字母丢失或只是运行,你可以修复它):

    # read
    file_path = os.path.join(d, fname)
    with open(file_path, 'r') as f: # 'r' is read can be skipped
        try:
            t = json.load(f)
        except Exception as e:
            print('%s %s' % (e, file_path))
    
    for i in t:
        tmp[i] = t[i]
    
    # write
    with open(file_path, 'w') as f:
        json.dump(tmp, f)        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多