微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

货币 Discord.py Bot 文件问题

如何解决货币 Discord.py Bot 文件问题

这是我的代码

@client.command()
async def beg(message):
    x = message.author.id
    idk = str(x) + ".wallet"
    file = open(idk,"w")
    file.close()
    file = open(idk,"r")
    first = file.read(1)
    if not first:
        file.close()
        file = open(idk,"w")
        file.write(str(0))
    file.close()
    file = open(idk,"r")
    money1 = file.readline()
    money1 = int(money1)
    a = random.randint(1,750)
    money1 = money1 + a
    print(money1)
    money1 = str(money1)
    print(money1)
    file.close()
    file = open(idk,"w")
    print(money1)
    file.write(money1)
    print(money1)
    file.close()
    await message.channel.send(f"You got {a} dollars from begging congrats")


@client.command()
async def bal(message):
    x = message.author.id
    idk = str(x) + ".wallet"
    file = open(idk,"r")
    moni = file.readline()
    await message.channel.send(f'You have {moni} in your wallet right Now.')

请假设我拥有所有必要的导入。 我认为问题在于这几行:

if not first:
    file.close()
    file = open(idk,"w")
    file.write(str(0))

即使文件不是空的,它仍然会重写文件并写入 0。不过我不知道如何解决这个问题。先感谢您!感谢所有帮助。

解决方法

问题在于文件打开模式 w 打开文件并重写整个内容。如果要添加字符串,必须以追加模式打开。

with open('file.txt','a') as f:
    f.write('something')

这会将 something 添加到文件中。

如果要修改文件

with open('file.txt','r') as f:
    file_str = f.readlines()
modify(file_str)
with open('file.txt','w') as f:
    f.write(file_str)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。