Search Functionality in a text file

I have a text file that has 2 columns in it, username and amount.

bigdonald 1.5
donald 2

with open('d:/onedrive/python/invoiceAudit/audit_' + filename_date + '-' + login_time + '.txt', 'r', encoding='utf-8') as notepad_customer_credit:
    
        for line in notepad_customer_credit:
            fields = line.split("\t")

            if fields[0].find(invoiceUsername) > -1:
                availableCredit = fields[1]

I open the text file, I line split \t. I’m trying to find the amount of credit the username donald as. My code returns bigdonald, because donald is in bigdonald and b comes before d. I’m stuck trying to get the search to work properly. Can anyone help?

To make the code more readable, you might want to replace

fields = line.split("\t")

by

name, credit = line.split("\t")

Next, if name does not include any spaces at the beginning or the end, you could simply write

if name == invoiceUsername:
    availableCredit = credit

if name might have been extracted with some extra spaces, then do

if name.strip() == invoiceUsername ...

By Myster Thomas via Discussions on Python.org at 20Aug2022 19:12:

I have a text file that has 2 columns in it, username and amount.

bigdonald 1.5
donald 2
[…]
if fields[0].find(invoiceUsername) > -1:
availableCredit = fields[1]

I open the text file, I line split \t. I’m trying to find the amount
of credit the username donald as. My code returns bigdonald, because
donald is in bigdonald and b comes before d. I’m stuck trying to get
the search to work properly. Can anyone help?

You’re testing with str.find, which locates a substring in a larger
string. It sounds like you just want equality:

if fields[0] == invoiceUsername:

Cheers,
Cameron Simpson cs@cskk.id.au