Python(Flask)在文件末尾写入不需要的字符

时间:2016-04-18 03:18:50

标签: python json flask

我有一个Flask函数,可以读取config.json文件,如下所示:

(对不起,我想我已经很好地解释了每一步)

{
    "tip": {
        "models": [
            "Gzip81", 
            "Gzip91"
        ]
    }, 
    "file_upload_dir": "input", 
    "sip": {
        "models": [
            "AnZip12", 
            "AnZip22"
        ]
    }, 
    "lip": {
        "models": [
            "iZip-20", 
            "iZip-160"
        ]
    }
}

我有一个update()函数可以打开文件并将新数据写入文件,如下所示:

with open('config.json', 'r+') as f:
        new_data = {
            "file_upload_dir": new_settings['upload_directory'],
            "tip": {"models": new_settings['tip_models']},
            "sip": {"models": new_settings['sip_models']},
            "lip": {"models": new_settings['lip_models']}
        }
        f.seek(0)  # <--- should reset file position to the beginning.
        json.dump(new_data, f, indent=4)

当我向JSON中的密钥添加更多数据时,它可以正常工作并正确写入文件:

{
        "tip": {
            "models": [
                "Gzip81", 
                "Gzip91",
                "StackOverflow" # <- new value
            ]
        }, 
        "file_upload_dir": "input", 
        "sip": {
            "models": [
                "AnZip12", 
                "AnZip22",
                "StackOverflow" # <- new value
            ]
        }, 
        "lip": {
            "models": [
                "iZip-20", 
                "iZip-160",
                "StackOverflow" # <- new value
            ]
        }
    }

但是,当我尝试从键中删除相同的"StackOverflow"条目时,通过使JSON文件无效,文件末尾会写入一些奇怪的数据:

    {
            "tip": {
                "models": [
                    "Gzip81", 
                    "Gzip91"

                ]
            }, 
            "file_upload_dir": "input", 
            "sip": {
                "models": [
                    "AnZip12", 
                    "AnZip22"
                ]
            }, 
            "lip": {
                "models": [
                    "iZip-20", 
                    "iZip-160"
                ]
            }
        }ackOverflow" # <-- where does this come from???
        ]
    }
} 

我得到的Flask错误是:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 369, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 30 column 13 - line 34 column 2 (char 529 - 576)

0 个答案:

没有答案