如何搜索和存储在数据中找到的行号?(Python)
我目前正在为我当地的慈善机构开发一个项目,我想问一下如何将该项目付诸实施 1) 在记事本文件中搜索特定单词 2) 存储在哪一行上找到该名称 到目前为止,我的代码是:如何搜索和存储在数据中找到的行号?(Python),python,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":
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”,并存储在哪一行找到该名称?我知道我可能会遇到困惑,但如果你不明白,请留下评论,我会回答你不明白的!提前谢谢 非常基本
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)
你想模仿grep吗?那是什么@devnullIt看起来您正试图编写一个“数据库”。有很多好的免费数据库可用,从Sqlite到Postgresql;为什么要重新发明轮子?谢谢,我现在会检查它们的。我如何将找到的线存储到变量中?(顺便说一句,非常感谢!)