Cody Roberts
Cody Roberts

Reputation: 5

Python Search file for a string and get the string's line number

so im writing a login system with python and i would like to know if i can search a text document for the username you put in then have it output the line it was found on and search a password document. if it matches the password that you put in with the string on that line then it prints that you logged in. any and all help is appreciated.in my previous code i have it search line one and if it doesnt find the string it adds one to line then repeats till it finds it. then it checks the password file at the same line

def checkuser(user,line):  # scan the username file for the username
    ulines = u.readlines(line)
    if user != ulines:
        line = line + 1
        checkuser(user)
    elif ulines == user:
        password(user)

Upvotes: 0

Views: 1151

Answers (2)

Kaustav Datta
Kaustav Datta

Reputation: 403

fucntion to get the line number. You can use this how you want

def getLineNumber(fileName, searchString):
    with open(fileName) as f:
        for i,line in enumerate(f, start=1):
           if searchString in line: 
               return i
    raise Exception('string not found')

Upvotes: 2

Prashant Puri
Prashant Puri

Reputation: 2334

Pythonic way for your answer

f = open(filename)
line_no = [num for num,line in enumerate(f) if 'searchstring' in line][0]
print line_no+1

Upvotes: 4

Related Questions