Python,读取一个文件作为数字

2024-09-30 18:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用我的discord.py机器人做一个经济型的小游戏。 我将人的平衡保存在不同的文本文件中(bot是给我和其他3个朋友的)

现在,如果它读取文件并需要将两个数字相加作为变量,它会说: discord.ext.commands.errors.CommandInvokeError:命令引发异常:TypeError:int()参数必须是字符串、类似于对象的字节或数字,而不是“\u io.TextIOWrapper”

我希望它以数字形式读取文件

这是我的代码:

async def beg(ctx):
    file = open(ctx.author.name, 'w')
    number = ("10","25","69","75","100")
    begmoney = (random.choice(number))
    balance = open(ctx.author.name, "r")
    newmoney = begmoney + int(balance)
    await ctx.send(newmoney)
    file.write(newmoney)
    await ctx.send("you got " + begmoney )
    await ctx.send("your balance now is: " + file.read())

有人能帮我吗


Tags: 文件namesendnumber数字openawaitfile
1条回答
网友
1楼 · 发布于 2024-09-30 18:21:48

从代码中我得到的是,你试图得到一个随机数,并将其添加到文件中的余额中,然后将新的金额写回。 这是你应该做的吗:

async def beg(ctx):
    number = ("10","25","69","75","100")
    begmoney = (random.choice(number))
    balance = 0
    with open(ctx.author.name, 'r') as file:
        balance = file.read().strip()
    with open(ctx.author.name, 'w') as file:
        newmoney = begmoney + int(balance)
        await ctx.send(f'{newmoney}')
        file.write(f'{newmoney}')
        await ctx.send(f"you got {begmoney}"  )
        await ctx.send("your balance now is: " + file.read())

相关问题 更多 >