在文件中搜索一行,并在文本

时间:2018-05-06 09:11:12

标签: python string search field line

我有一个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.')

1 个答案:

答案 0 :(得分:0)

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