[英]Search a text file for a multi line string and return line number in Python
[英]Python Search file for a string and get the string's line number
所以我用python編寫了一個登錄系統,我想知道是否可以在文本文件中搜索您輸入的用戶名,然后讓它輸出在其上找到的行並搜索密碼文件。 如果它與您在該行上輸入的密碼相匹配,則會打印出您已登錄的信息。任何和所有幫助都將受到贊賞。在我之前的代碼中,我搜索了第一行,如果找不到該行,它將添加一個排隊,然后重復直到找到為止。 然后在同一行檢查密碼文件
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)
獲得行號的功能。 您可以根據需要使用它
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')
用Python方式解答
f = open(filename)
line_no = [num for num,line in enumerate(f) if 'searchstring' in line][0]
print line_no+1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.