У меня есть текстовый файл, который я хочу найти по «id». Каждая строка в файле содержит 5 полей (идентификатор, имя, возраст, рост, вес). Если поиск по идентификатору находит совпадение, я хочу отобразить каждое поле в соответствующей строке, как показано ниже:
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' ''
# 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.')