在Python中,如何访问特定行中文本文件中的数据?

2024-05-15 12:02:33 发布

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

一些背景-我正在为Discord创建一个机器人。这个命令,claim,将用于声明一个“作业”,或者本质上将他们不一致的用户名绑定到作业上。该命令将使用行号作为作业的标识符

我遇到的问题是,我只能使用此“for”函数访问job.txt文件的第一行。当我尝试访问其他线路时,我得到“此作业不存在!”错误

@bot.command()
async def claim(ctx, *, message=None):

    with open('job.txt', 'r+') as f:
        for num, line in enumerate(f, 1):
            if num == int(message):
                print(line)
                break
            else:
                print('This job does not exist!')
                break

当我像这样运行代码时


@bot.command()
async def claim(ctx, *, message=None):

    with open('job.txt', 'r+') as f:
        for num, line in enumerate(f, 1):
            if num == int(message):
                print(line)
                break

我可以访问每一条对我来说毫无意义的线路。不幸的是,我需要能够阻止某人申请一份不存在的工作


Tags: 命令txtmessageforasyncbot作业line
1条回答
网友
1楼 · 发布于 2024-05-15 12:02:33

在第一个示例中,在ifelse上有一个break。因此,循环总是在从文件中读取第一行后终止。我怀疑你想通过所有的线路找到匹配的信息

我建议跟踪您是否找到了工作,并在循环后处理:

@bot.command()
async def claim(ctx, *, message=None):

    found_job = False
    with open('job.txt', 'r+') as f:
        for num, line in enumerate(f, 1):
            if num == int(message):
                print(line)
                found_job = True
                break

    if found_job:
       # do your work here
    else:
       print("Uh-oh...didn't find the job")

相关问题 更多 >