在文件中搜索一行,并在单独的行上显示带有文本的结果



我有一个 txt 文件,我想搜索一个 'id'。文件中的每一行包含 5 个字段(id、姓名、年龄、身高、体重(。如果 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((: "功能允许用户从玩家.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 tt from fields
id_field = id_field.rstrip('tt')
name_field = name_field.rstrip('tt')
age_field = age_field.rstrip('t')
height_field = height_field.rstrip('tt')
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.')

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

最新更新