货币 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)