首页 > 解决方案 > 重新编辑 json 文件时的随机/空字符

问题描述

对于标题中对我的问题的模糊定义,我深表歉意,但我真的无法弄清楚我正在处理什么样的问题。所以,就这样吧。

我有 python 文件: edit-json.py

import os, json

def add_rooms(data):
    if(not os.path.exists('rooms.json')):
        with open('rooms.json', 'w'): pass

    with open('rooms.json', 'r+') as f:
        d = f.read()  # take existing data from file
        f.truncate(0)  # empty the json file
        if(d == ''): rooms = []  # check if data is empty i.e the file was just created
        else: rooms = json.loads(d)['rooms']
        rooms.append({'name': data['roomname'], 'active': 1})
        f.write(json.dumps({"rooms": rooms}))  # write new data(rooms list) to the json file

add_rooms({'roomname': 'friends'})'

这个python脚本基本上创建了一个文件rooms.json(如果它不存在),从json文件中获取数据(数组),清空json文件,最后将新数据写入文件。所有这些都是在函数 add_rooms() 中完成的,然后在脚本末尾调用该函数,非常简单。

所以,这就是问题所在,我运行了一次文件,没有发生任何奇怪的事情,即文件被创建并且其中的数据是:

{"rooms": [{"name": "friends"}]}

但是当再次运行脚本时会发生奇怪的事情。

我应该看到的:

{"rooms": [{"name": "friends"}, {"name": "friends"}]}

我看到的是: 上面的 json 前面有一堆“奇怪”的符号/字符

我很抱歉我不得不发布图片,因为由于某种原因我无法复制我得到的文字。

而且我显然不能再次运行脚本(第三次),因为 json 解析器由于这些字符而出错

我在在线编译器中获得了这个结果。在我的本地 Windows 系统中,我得到了额外的空白而不是那些额外的符号。

我不知道是什么原因造成的。也许我没有正确处理文件?还是由于 json 模块?还是我是唯一一个得到这个结果的人?

标签: pythonjsonfile-handling

解决方案


截断文件时,文件指针仍位于文件末尾。用于f.seek(0)移回文件的开头:

import os, json

def add_rooms(data):
    if(not os.path.exists('rooms.json')):
        with open('rooms.json', 'w'): pass

    with open('rooms.json', 'r+') as f:
        d = f.read()  # take existing data from file
        f.truncate(0)  # empty the json file
        f.seek(0)  #  <<<<<<<<< add this line
        if(d == ''): rooms = []  # check if data is empty i.e the file was just created
        else: rooms = json.loads(d)['rooms']
        rooms.append({'name': data['roomname'], 'active': 1})
        f.write(json.dumps({"rooms": rooms}))  # write new data(rooms list) to the json file

add_rooms({'roomname': 'friends'})

推荐阅读