EXTENDED ALGO:
As i can have in my csv some values with space: ", atleft,atright , both " , I patch the code of zmo as follow
if field.strip() == username:
and it's ok, thanks.
OLD FASHION ALGO
i had previously coded an 'old fashion' algorithm that takes care of any allowed separators ( here comma, space and newline),so i was curious to compare performances.
With 10000 rounds on a very simple csv file, i got:
------------------ algo 1 old fashion ---------------
done in 1.931804895401001 s.
------------------ algo 2 with csv ---------------
done in 1.926626205444336 s.
As this is not too bad, 0.25% longer, i think that this good old hand made algo can help somebody (and will be useful if more parasitic chars as strip is only for spaces)
This algo uses bytes and can be used for anything else than strings.
It search for a name not embedded in another by checking left and right bytes that must be in the allowed separators.
It mainly uses loops with ejection asap through break or continue.
def separatorsNok(x): return (x!=44) and (x!=32) and (x!=10) and (x!=13) #comma space lf cr # set as a function to be able to run several chained tests def searchUserName(userName, fileName): # read file as binary (supposed to be utf-8 as userName) f = open(fileName, 'rb') contents = f.read() lenOfFile = len(contents) # set username in bytes userBytes = bytearray(userName.encode('utf-8')) lenOfUser = len(userBytes) posInFile = 0 posInUser = 0 while posInFile < lenOfFile: found = False posInUser = 0 # search full name while posInFile < lenOfFile: if (contents[posInFile] == userBytes[posInUser]): posInUser += 1 if (posInUser == lenOfUser): found = True break posInFile += 1 if not found: continue # found a fulll name, check if isolated on left and on right # left ok at very beginning or space or comma or new line if (posInFile > lenOfUser): if separatorsNok(contents[posInFile-lenOfUser]): #previousLeft continue # right ok at very end or space or comma or new line if (posInFile < lenOfFile-1): if separatorsNok(contents[posInFile+1]): # nextRight continue # found and bordered break # main while if found: print(userName, "is in file") # at posInFile-lenOfUser+1) else: pass
to check: searchUserName('pirla','test.csv')
As other answers, code exit at first match but can be easily extended to find all.
HTH