在 .txt 文件中存储和删除 Discord 用户 ID

问题描述 投票:0回答:1

我需要制作一个机器人,将用户的 UserID 存储在 txt 文件中,然后在用户执行命令时删除该 UserID。

此代码查看包含所有用户的 UserID 的文本文件。然后它会找到执行该命令的用户的 UserID - 然后应该从文件中删除该用户的 UserID。但是,此命令不起作用 - 因为它删除了文本文件的全部内容 - 当它只应该删除一行时。我在论坛上浏览了一个小时来解决这个问题:但没有任何效果。

@client.command()
async def unreserve(ctx):
    author = (ctx.author.id)

    with open('ReservedUsers.txt', 'r') as f:
        lines = f.readlines()
    with open('ReservedUsers.txt', 'w') as f:
        for line in lines:
            if line == author:
                f.write(line)

这是“ReservedUsers.txt”文件的示例:

000000000000000001
000000000000000002
000000000000000003
python python-3.x discord discord.py
1个回答
0
投票

这应该有效:

@client.command()
async def unreserve(ctx):
    author = (ctx.author.id)
    with open(f"ReservedUsers.txt", "r") as f:
        lines = f.readlines()
    with open(f"ReservedUsers.txt", "w") as f:
        for line in lines:
            if line.strip("\n") != author:
                f.write(line)
© www.soinside.com 2019 - 2024. All rights reserved.