【问题标题】:random/empty characters while re-editing a json file重新编辑 json 文件时的随机/空字符
【发布时间】:2020-09-29 17:06:56
【问题描述】:

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

我有 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 解析器由于这些字符而出错

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

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

【问题讨论】:

    标签: python json file-handling


    【解决方案1】:

    截断文件时,文件指针仍位于文件末尾。使用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'})
    

    【讨论】:

    • 感谢@Mike67 我做到了,它帮助了。我使用 f.tell() 来查看截断文件后的位置,而第二次我没有看到 0 作为位置。
    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多