Discord Bot逐行发送文本文件

2024-03-29 09:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用discord命令,它将整个文本文件逐行写入聊天室,我尝试使用它,但不知为什么它不能正常工作

    file = open('story.txt', 'r')

    @client.command(alisases = ['readfile'])
     async def story(ctx):
        for x in file:
            await ctx.send(file)

它运行,但只写入以下行:

Picture

<_io.TextIOWrapper name='story.txt'mode='r'encoding='cp1250'>


Tags: 命令txtclientforasyncdefopencommand
1条回答
网友
1楼 · 发布于 2024-03-29 09:39:55

您发送的是文件对象的字符串表示形式,而不是其中的行

你可以这样做:

@client.command(alisases = ['readfile'])
async def story(ctx):
    with open('story.txt', 'r') as story_file:
        for line in story_file:
            await ctx.send(line)

另外,使用with open语法是一种很好的做法,因为它可以确保文件被正确关闭

相关问题 更多 >