【问题标题】:Read a specific line in a file (Python)读取文件中的特定行(Python)
【发布时间】:2021-10-28 20:10:46
【问题描述】:

我拥有一个 discord.py 机器人。我做了一些命令,可以创建一个带有一些简单功能的文件。我有一个命令让我读取文件,但是,我想改进它。我希望机器人读取文件的特定行。就像我说+file read test txt 9 一样,机器人会在第 9 行读取文件 test.txt。

我在 cog (cogs/owner.py) 中使用命令组。名为“file”的命令组具有 False invoke_without_command() (@commmands.group(invoke_without_command=False))

我首先尝试将“line”变量放入await ctx.send(f.read(line)),但没有成功。

这是代码的 MRE(最小可重现示例):

cogs/owner.py

from discord.ext import commands
import discord

class Owner(commands.Cog):
    # the init function

    @commands.group(invoke_without_command=False)
    async def file(self, ctx):
        print="‎ ‎"

    @file.command()
    async def read(self, ctx, filename, extension, line=None):
        if line == None:
            f = open(f"{filename}.{extension}", "r")
            await ctx.send(f.read())
        else:
            f = open(f"{filename}.{extension}", "r")
            await ctx.send(f.read(line))
            """
            also tried this:
            await ctx.send(f.read(type(Line)))
            """"

#setup function

【问题讨论】:

标签: python discord discord.py bots


【解决方案1】:

read 函数不理解行号。你想要这样的东西:

await ctx.send(f.readlines()[line-1])

...- 1 是因为 Python 数组(如 readlines 返回的行数组)从 0 开始计数,但文本文件行号通常从 1 开始。

虽然如果文件没有那么多行,这会引发异常,因此您可能需要添加 except 子句来处理这种情况。

【讨论】:

    猜你喜欢
    • 2015-09-06
    • 2015-01-23
    • 1970-01-01
    • 2017-07-16
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多