0

I am trying to read a .txt file with hundreds of names and i want to look for a particular name.

For example, I have several names like

John simons
kumar ayush singh
peter calpidi
david brown

etc and I want to look for a substring ayush and if the substring exists I want to return complete string like kumar ayush singh.

I tried something like this:

try:
    with open('D:\\Any One\\name_list.txt') as names:
        for row in names:
            if row.find(request.strip()) != -1:
               results = row
               print(row)
except Exception as err:
    print(err)

but got an error :

'charmap' codec can't decode byte 0x81 in position 4467: character maps to undefined
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94

1 Answers1

0

REF: https://docs.python.org/3.9/library/functions.html#open

Review the errors options for the one you prefer. In the code, I put replace because it will put a marker where the error occurred and continue to process the file.

try:
    with open('D:\\Any One\\name_list.txt',errors='replace') as names:
        for row in names:
            if row.find(request.strip()) != -1:
               results = row
               print(request)
except Exception as err:
    print(err)
Carl_M
  • 861
  • 1
  • 7
  • 14