我想打开一个json文件,为了保护其中的安全,几秒钟后,我想再次删除它。我已经在dpy支持中问过。他们说,我无法在写入模式下打开文件。但是,无论如何我如何打开文件?或如何摆脱这种写入模式?
我尝试过:
@bot.command()
@commands.has_permissions(administrator=True)
async def knastmute(ctx, member: discord.Member = None, arg1= None, *, arg2=None):
guild = bot.get_guild(597135532111167622)
knastmute = get(guild.roles, id=696100186149224545)
Knast = 686657535427739804
guildemojisbtv = bot.get_guild(712671329123303504)
Epositiv = get(guildemojisbtv.emojis, id=712679512873369610)
Eerror = get(guildemojisbtv.emojis, id=713187214586282054)
if member:
if any(role.id == Knast for role in member.roles):
if arg1 == '1m':
with open(r'./knastmuteusers.json', 'r')as f:
users = json.load(f)
if not f"{member.id}" in users:
users[member.id] = f"{member}: {arg1}"
with open(r"./knastmuteusers.json", 'w') as f:
json.dump(users, f, indent=4)
await member.add_roles(knastmute)
await asyncio.sleep(5)
with open(r'./knastmuteusers.json', 'r')as f:
users = json.load(f)
del users[member.id]
with open(r"./knastmuteusers.json", 'w') as f:
json.dump(users, f, indent=4)
await member.remove_roles(knastmute)
我收到此错误:
I get this error:
```Ignoring exception in command knastmute:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "F:\DiscordBot\PyCharm\blacktv.py", line 2327, in knastmute
users = json.load(f)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
发生的事情是您正在尝试打开文件,但仍在打开该文件。从上下文管理器中取消缩进会自动关闭文件。
错误本身表明文件格式不正确,很可能看起来像这样:
{
如果您未将有效格式的数据写入.json,则会发生这种情况。
这里是一个示例命令,它多次读取/写入文件:
import os # necessary if you wish to check the file exists
@bot.command()
async def cmd(ctx):
if os.path.isfile("file.json"):
with open("file.json", "r") as fp:
data = json.load(fp) # loads the file contents into a dict with name data
data["users"].append(ctx.author.id) # add author's id to a list with key 'users'
else: # creating dict for json file if the file doesn't exist
data = {
"users": []
}
data["users"].append(ctx.author.id)
# outside of if statement as we're writing to the file no matter what
with open("file.json", "w+") as fp:
json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for formatting
print(data) # you're still able to access the dict after closing the file
await ctx.send("Successfully updated a file!")
参考:
json.dump()
json.dump()