python - 重新编辑 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 解析器由于这些字符而出错
我在在线编译器中获得了这个结果。在我的本地 Windows 系统中,我得到了额外的空白而不是那些额外的符号。
我不知道是什么原因造成的。也许我没有正确处理文件?还是由于 json 模块?还是我是唯一一个得到这个结果的人?
解决方案
截断文件时,文件指针仍位于文件末尾。用于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'})
推荐阅读
- html - 如何使所有项目的宽度相同但尽可能小?
- javascript - 将某些内容导入/导出到 app.svelte 时,Svelte 应用程序显示空白页面
- python - X 从 1 到 N 的倍数
- excel - 将大文件拆分成多个小文件excel VBA
- django-rest-framework - NOT NULL 约束失败:api_article.author_id、Django_RestFramework Nested Serializers
- python - 如何将 discord.py 任务放入 cog 并运行它?
- macos - OMNeT++ 在 macOS 上缺少“可可”
- python - 如何使用 python 在 Web 浏览器中显示重定向 url
- typescript - TypeScript 或 ES6 版本的 lodash _.set() 用于深度对象属性分配跳过空检查
- css - 在 SCSS 中编写媒体查询