【问题标题】:Suggestions on making the code read the csv files关于使代码读取 csv 文件的建议
【发布时间】:2021-06-12 00:12:42
【问题描述】:

所以我有一个不和谐机器人的代码,它允许审核人员休假然后返回,命令取消他们的审核角色并给他们一个休假角色,但是有员工的资历级别,所以每个人都有自己的自己的命令。

该代码应该将使用该命令的用户的 ID 记录到特定的 CSV 文件中,但是在返回的命令中,我不相信它正在存储或读取该 ID 的文件,即版主可以使用他们的命令继续休假,但是他们可以使用管理员返回命令给他们一个管理员角色。

我相信这是因为代码没有在所需文件中读取或写入,这是我拥有的代码;

    @client.command()
    @commands.has_role('Moderator')
    async def slm(ctx, member: discord.Member = None):
        if not member:
            member = ctx.author
        loa = ctx.guild.get_role(848032714715561985)
        mod = ctx.guild.get_role(848032880709074944)
        await member.add_roles(loa)
        await member.remove_roles(mod)
        file = open("modRecord.csv", "w")
        file.write(str(ctx.author.id))
        file.close()
        await ctx.send("I have filed your Leave, take care, we look forward to your return!")
    
    
    @client.command()
    async def srm(ctx, member: discord.Member = None):
        if not member:
            member = ctx.author
        mod = ctx.guild.get_role(848032880709074944)
        loa = ctx.guild.get_role(848032714715561985)
        found = False
        with open('modRecord.csv', 'r') as file:
            reader = csv.reader(file)
            for row in reader:
                if row[0] == str(ctx.author.id):
                    found = True
                    break
        if found is False:
            await member.add_roles(mod)
            await member.remove_roles(loa)
            await ctx.send("Welcome back!")
        else:
            await ctx.send("We do not have history of you having a Moderator role.")

其他版主角色的命令是相同的,只是不同的文件来存储他们的id,每个命令本质上都有自己的文件。

谁能告诉我为什么它不能在文件中读取或写入,或者建议一个更好的记录系统?

【问题讨论】:

  • 通常数据库比 csv 更适合存储应用程序
  • 如果你把这堵文字墙分成几个段落,并使用标点符号正确地结束句子,这样一来一个句子在哪里结束,一个新句子从哪里开始就很清楚了。句子以. 结尾,下一句的第一个单词应大写。我会尝试修复它,但我担心这样做会导致您的要求出现错误。您应该edit 来解决这些问题。

标签: python python-3.x discord.py


【解决方案1】:

数据库确实是存储此类数据的更好方法,但使用 CSV 则没有这样的问题。我发现了 1 个错误,即每次您存储成员/作者 ID 时,您在打开它时都在使用“写入”模式。

file = open("modRecord.csv", "w")
file.write(str(ctx.author.id))

这会清除 csv 中存在的所有先前数据,然后写入新数据。 以下是一些其他可能的方法:

使用追加模式:通过这种方式,您可以在文件的最后添加 id。

file = open("modRecord.csv", 'a')
file.write(str(ctx.author.is))
file.close()

使用 pandas:Pandas 是一个 python 库,可以轻松读取/写入 csv 文件。使用它将 csv 视为电子表格。还有其他库,例如 Openpyxl。但我更喜欢熊猫。

先读后写文件:首先读取文件,将其内容存储在变量中,在内容中进行任何您想要的迭代,例如替换任何行、删除任何行、添加两行之间的一行,等等,然后最后将变量再次写入文件。

file=open('modRecord.csv','r')
file_content=file.read()
make changes in file_content
new_file=open('modRecord.csv','w')
new_file.write(file_content)
file.close()
new_file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    相关资源
    最近更新 更多