Extract specific lines which changes in different text files
Solution 1:
Since the data you need is in the same position after a team name, you could loop through it and store the team name in the variable team_num
and initialize a key in a dictionary as a list
. Then you could append the respective elements to the current key.
with open("data.txt") as file:
data = file.readlines()
data = [d.strip() for d in data]
data_dict = {}
team_num = ""
for line in data:
if "Team" in line:
team_num = line
data_dict[team_num] = []
else:
data_dict[team_num].append(line.split()[1])
print(data_dict)
Input:
Team 2
dff30000 player1 (Random)
dff30001 player2 (Random)
Team 3
1AA6E030 player3 (Random)
1AB6E030 player4 (Random)
Output:
{'Team 2': ['player1', 'player2'], 'Team 3': ['player3', 'player4']}