首页 > 解决方案 > 为什么我的 json 文件总是变成一串随机单词?(Python)

问题描述

所以我正在用 json 和 discord.py 在 python 中制作一些评分系统类型的东西,这是它的代码:

import json

def getPoints(bot, user):
    f = open('points.json', 'r')
    points = json.load(f)

    name = str(user)
    f.close()
    return points.get(name)

#later on down the line

@bot.group()
async def pointSystem(ctx):
    pass

@pointSystem.command()
async def enable(ctx):
    f = open('points.json', 'r')
    points = json.load(f)
    if points.get(str(ctx.author)) != None:
        await ctx.send('Already enabled for this user!')
        return
    io = await ui.prompt(ctx, 'This command enables the point system\nAre you sure you want to enable this?')
    if io == 'yes':
        await ctx.send('Ok, enabling...')
        points[str(ctx.author)] = 0
        f.close()
        f = open('points.json', 'w')
        json.dump(points, f, indent=4)
        f.close()
        await ctx.send('Enabled for this user!')
    else:
        await ctx.send('Alright, stopping command execution...')
        f.close()

在 points.json 我应该有:

{}

这就是我最初放在那里的内容,但有时,我查看 points.json 并看到一个带有一些随机单词的字符串。它不会给出任何类型的错误,它只是按照我的描述进行,这没有多大意义,因为我认为我没有任何代码可以将其设置为任何类型的字符串。我没有复制代码,因为我不知道这个问题的真正罪魁祸首,我会指出你做的事情就像我所做的那样,用这个评分系统创建一个不和谐的机器人,但我真的不认为即使这样也会重现它。

编辑:好的,这变得非常奇怪。3 个月后,使用全新的代码,我的根目录中仍然有一个名为“points.json”的文件,其中包含我上面提到的随机字符串,这实际上没有任何意义。即使我删除它,几周后它也会回来。

标签: pythonjsondiscord.py

解决方案


推荐阅读