Python,读取一个文件作为number



我尝试在我的《discord.py bot》中创造一个经济小游戏。我把人的余额保存在不同的文本文件中(bot是给我和其他3个朋友的)

现在,如果它读取文件并需要将两个数字相加作为一个变量,它会说:discord.ext.commands.errors.CommandInvokeError: Command引发了一个异常:TypeError: int()参数必须是字符串、类字节对象或数字,而不是'_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())

有人能帮我吗?

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

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())

相关内容

最新更新