从'txt'文件导入某些详细信息

我有一个 .txt 文件,其中名称和地址以下列格式显示:

Sam, 35 Marly Road
...
...

我希望能够搜索 Sam 并找到 35 Marly Road .

这是我到目前为止的代码:

name = input("Please insert your required Client's name: ")
if name in open('clientAddress.txt').read():
  print ("Client Found")`

这将检查输入的ID是否在文件中可用,但它不会打印该地址 . 如何更改它,以便找到名称并打印地址?

回答(2)

2 years ago

作为快速解决方案 - 见下文

username = input()

with open('clientRecords.txt', 'r') as clientsfile:
    for line in clientsfile.readline():
        if line.startswith("%s, " % username):
            print("Cient %s found: %s" % (username, line[len(username) + 2:]))
            break

2 years ago

简单解决方案

username = input()
with open('clientRecords.txt', 'r') as clientsfile:
    for line in clientsfile:
        if line.startswith("%s, " % username):
            print("Client %s found: %s" % (username, line.split(",")[1]))
            break

For循环遍历文件行,当我们发现行以所需的客户端名称开始时,我们打印地址和中断循环 .