Discord机器人银行功能开发:文本文件行增删改问题
解决Discord机器人银行余额更新与查询问题
核心操作思路
文本文件无法直接修改某一行内容,必须遵循「读全量内容→修改目标行→覆盖写入全量内容」的流程。针对你的需求,我们需要:
- 读取文件中所有派对的银行数据
- 匹配目标派对,更新其总金额
- 将修改后的所有数据重新写入文件
完整代码实现
1. 完善bankadd命令(支持余额累加)
@commands.command() async def bankadd(self, ctx, party, add_amount): try: add_amount = int(add_amount) party = str(party).strip() except ValueError: await ctx.send("请输入有效的数字金额!") return if party == "help": # 读取已存在的派对列表 parties = [] try: with open("INBank.txt", "r") as f: for line in f: if line.strip(): parties.append(line.split()[0]) except FileNotFoundError: pass await ctx.send(f"当前已开通银行的派对:{', '.join(parties) if parties else '暂无'}") await ctx.send("请选择其中一个派对进行操作") return # 处理余额更新 updated_lines = [] found = False try: with open("INBank.txt", "r") as f: for line in f: line = line.strip() if not line: updated_lines.append(line) continue # 拆分每行的派对名称和金额 parts = line.split() if len(parts) >= 4 and parts[0] == party: # 匹配到目标派对,更新金额 current_total = int(parts[3]) new_total = current_total + add_amount updated_lines.append(f"{party} bank total: {new_total}") found = True else: updated_lines.append(line) # 如果是新派对,添加到文件末尾 if not found: updated_lines.append(f"{party} bank total: {add_amount}") # 将修改后的内容写入文件 with open("INBank.txt", "w") as f: f.write('\n'.join(updated_lines)) await ctx.send(f"派对{party}的银行余额已更新!当前总额:{new_total if found else add_amount}") except Exception as e: await ctx.send(f"操作失败:{str(e)}")
2. 添加bankcheck查询命令
@commands.command() async def bankcheck(self, ctx, party): party = str(party).strip() try: with open("INBank.txt", "r") as f: for line in f: line = line.strip() if not line: continue parts = line.split() if len(parts) >=4 and parts[0] == party: await ctx.send(f"派对{party}的银行总余额:{parts[3]}") return await ctx.send(f"未找到派对{party}的银行记录!") except FileNotFoundError: await ctx.send("暂无任何银行记录!") except Exception as e: await ctx.send(f"查询失败:{str(e)}")
关键知识解析
文件操作模式:
r:只读模式,用于读取文件内容w:写入模式,会清空原有内容后写入新内容(我们用它来覆盖更新)a:追加模式,在文件末尾添加内容(适合新增派对)- 用
with语句操作文件:会自动关闭文件,避免资源泄漏,比手动open/close更安全
文本行处理逻辑:
文本文件是按字节流存储的,修改中间行的内容会导致后续内容被覆盖,所以必须把所有内容读到内存中修改,再重新写入。异常处理:
加入try-except可以捕获文件不存在、输入非数字等异常,避免机器人崩溃,同时给用户明确的错误提示。
内容的提问来源于stack exchange,提问作者ph3onixleader
相关产品推荐
相关产品推荐

