简体   繁体   中英

How do you access data in a text file in a specific line in Python?

Some background - I am creating a bot for Discord. This command, claim , will be used to claim a "job", or essentially tie their discord username to the job. The command will use the line number as the identifier for the job.

The problem I am having is that I can only access the first line in the job.txt file using this 'for' function. When I try to access the other lines, I get the 'This job does not exist!' error.

@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

When I run the code like this...


@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

I can access each line which doesn't really make sense to me. Unfortunately, I need to be able to prevent someone from claiming a job that doesn't exist.

In your first example you have a break on the if and on the else . As a result, the loop always terminates after reading the first line from the file. I suspect you want to go through all lines to find the matching message.

I would suggest keeping track of whether you found the job and handling that after the loop:

@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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM