Search code examples
pythonrandomgeneratortxt

How to find a certain string/name in a txt file?


So im making a name generator/finder, So for the find command i want to find that name in the txt file with the line number! So how do i find the name with the line number?

line = 0

names = open(r"names.txt", "r")
name1 = names.readlines()

uname = input("Please enter the name you want to find: ")
for name in name1:
  try:
    print(name)
    print(line)
    if name == uname:
      print(f"Found name: {name} \nLine No. {line + 1}")
    else:
      line = line + 1
  except:
    print("Unable to process")

But it seems to not work except if you write the last name in file it works. So could give any help?

EDIT: Ive found a way so you can reply if you want to for further people running into the problem!


Solution

  • Try this:

    with open("names.txt", "r") as f:
        file_contents = names.read().splitlines()
    
    uname = input("Please enter the name you want to find: ")
    
    for line, row in enumerate(file_contents):
        if uname in row:
            print('Name "{0}" found in line {1}'.format(uname, line))