如何在.txt文件中搜索字符串并打印字符串所在的行?(Python)



上面的问题。我试图在Python3中的控制台内部创建一个联系人簿;搜索";命令,但我所尝试的一切都不起作用。我在网上也没有发现任何有用的东西。

f = open("C:/Users/Yonas/Documents/PythonProject.txt", "a")
entry = input()
i = 0
def add():
print("Please type in the name of the person you want to add.")
in2 = input()
f.write(in2 + " | ")
print("Please type in the location of the person you want to add.")
in3 = input()
f.write(in3 + " | ")
print("Please type in some additional information.")
in4 = input()
f.write(in4 + "n")
def search():
line_number = 0
print("Please type in the name of the person you're looking for.")
inSearch = input()
list_of_results = list(f)

# The code should be here
if entry.startswith("add"):
add()
if entry.startswith("search"):
search()

希望你能理解我的问题。

对原始代码片段进行稍微修改的版本:

contact_book_path = "collection.txt"

def add():
with open(contact_book_path, "a") as contact_book_fp:
contact = ""
name = input("Please type in the name of the person you want to add.n")
contact += name + " | "
location = input("Please type in the location of the person you want to add.n")
contact += location + " | "
info = input("Please type in some additional information.n")
contact += info + "n"
contact_book_fp.write(contact)

def search():
with open(contact_book_path, "r") as contact_book_fp:
name_search = input(
"Please type in the name of the person you're looking for.n"
)
for line_no, contact in enumerate(contact_book_fp.readlines()):
name, location, info = contact.split(" | ")
if name == name_search:
print("Your contact was found at line " + str(line_no))
return
print("Your contact was not found! :(")

entry = input("What kind of operation would you like to do (add/search)?n")
if entry.startswith("add"):
add()
if entry.startswith("search"):
search()

我建议您在真正需要时打开它以进行正确的操作,而不是以附加模式打开文件。因此,在add中进行追加和在search中进行读取。

在打开文件并询问要搜索的名称后的search函数中,可以使用标准的file.readlines()方法迭代文件中的行。我还使用了enumerate函数来获得一个与行一起运行的索引,以后我可以将其用作行号

将所有这些放在一起后,基本上可以以任何方式增强查找逻辑。

最新更新