首页 > 解决方案 > 在文件中搜索一行并将结果显示在带有文本的单独行上

问题描述

我有一个 txt 文件,我想搜索一个“id”。文件中的每一行包含 5 个字段(id、name、age、height、weight)。如果 id 搜索找到匹配项,我想在匹配行中显示每个字段,如下所示:

    x 'player/s have been found:'
    print('Player ID: ', id)
    print('Player name: ', name)
    print('Age: ', age)
    print('Height: ', height)
    print('Weight: ', weight)

到目前为止,我只能将匹配的行打印为一行,而不能将各个字段拉到不同的打印行上。任何帮助将不胜感激!

这是我到目前为止所拥有的,但 python 似乎无法读取任何匹配项..

def search_enter_id(): '''函数允许用户从 Players.txt 文件中搜索玩家 ID'''

# Create a bool variable to use as a flag
found = False

# Get search value
my_string = input('Please enter the player ID you want to search: ')

# Open a file for reading
player_file = open('Players.txt', 'r')

# Read the first records ID field
id_field = player_file.readline()

# Read the rest of the file
while id_field != '':
    # Read the name field
    name_field = player_file.readline()

    # Read Age field
    age_field = player_file.readline()

    #Read Height field
    height_field = player_file.readline()

    #Read weight field
    weight_field = player_file.readline()

    # Strip the \t\t from fields
    id_field = id_field.rstrip('\t\t')
    name_field = name_field.rstrip('\t\t')
    age_field = age_field.rstrip('\t')
    height_field = height_field.rstrip('\t\t')
    weight_field = weight_field.rstrip('\n')

    # Determine whether this record matches the search value
    if id_field == my_string:
        # Display the record
        print('Player ID: ', id_field)
        print('Player name: ', name_field)
        print('Age: ', age_field)
        print('Height: ', height_field)
        print('Weight: ', weight_field)
        print()
        # Set the found flag to true
        found = True

    # Read the next ID field
    id_field = player_file.readline()

# Close the file
player_file.close()

# If the search value was not found in the file
# display a message
if not found:
    print('That ID was not found in the file.')

标签: pythonstringsearchfieldline

解决方案


匹配一行后,将其拆分。
array = line.split('xxx')
* 用你的分隔符替换 xxx
现在你可以使用你的数组来取出各个字段。


推荐阅读