如何搜索和存储在数据中找到的行号?(Python)

2024-04-25 16:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在为我当地的慈善机构开发一个项目,我想问一下如何让这个项目成功 1) 在记事本文件中搜索特定单词 2) 存储在哪一行上找到该名称

到目前为止我的代码是:

import time

def AddToDatabase():
    print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
    ATD = input(": ")
    if ATD == "A" or ATD == "a":

    Name = input("\nEnter Name of Member [First Name and Surname]: ")
    with open("Name.txt", "a") as N:
        N.write("\n{}".format(Name))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    print ("\nEnter Address of "+Name+" all on one line")
    print ("In format [Include Commas]")
    print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
    Address = input("\n: ")
    with open("Address.txt", "a") as A:
        A.write("\n{}".format(Address))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    Home_Number = input("\nEnter Home Number of "+Name+": ")
    with open("Home Number.txt", "a") as HN:
        HN.write("\n{}".format(Home_Number))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
    with open("Mobile Number.txt", "a") as MN:
        MN.write("\n{}".format(Mobile_Number))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    Email_Address = input ("\nEnter Email Address of "+Name+": ")
    with open("Email Address.txt", "a") as EA:
        EA.write("\n{}".format(Email_Address))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
    with open("Medical Dietry Needs.txt", "a") as MDN:
        MDN.write("\n{}".format(Dietry_Needs))
    time.sleep(1)
    print ("\nAdding...")
    time.sleep(1)

    print ("All information for "+Name+" has been added. Redirecting Back To Main...")
    time.sleep(5)
    Main()

elif ATD == "B" or ATD == "b":
    Main()

def CheckDatabase():
    print ("\nSPACE SAVED")

def Main():
    print ("\nSVA of UK Database")
    while True:
    print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
    choice = input(": ")

    if choice == "A" or choice == "a":
        CheckDatabase()

    elif choice == "B" or choice == "b":
        AddToDatabase()

    elif choice == "C" or choice == "c":
        break

    else:
        print ("Invalid Input")
        Main()

Main()

如何在txt文件中搜索例如“John Smith”,并存储在哪一行找到该名称?我知道我可能会遇到困惑,但如果你不明白,请留下评论,我会回答你不明白!提前谢谢!你知道吗


Tags: ofnametxtformatnumberinputtimeaddress
1条回答
网友
1楼 · 发布于 2024-04-25 16:40:53

很基本。。。你知道吗

found_line = None
with open(filename) as f:

    pattern = "john smith"
    for i, line in enumerate(f):
        if pattern in line:
            found_line = i
            print "Found %s in %i" % (pattern, i)

相关问题 更多 >