从“txt”fi导入某些详细信息

2024-05-07 14:00:41 发布

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

我有一个.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是否在文件中可用,但不会打印地址。如何更改它,以便它找到名称并打印地址?你知道吗


Tags: 文件代码nametxt名称clientinputyour
2条回答

简单的解决方案

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循环遍历文件行,当我们发现行以所需的客户机名称开始时,我们打印地址并中断循环。你知道吗

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

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

相关问题 更多 >