Ask coding questions

← Back to all posts
How do I pull an average from a text file?
RILEYSENFTEN

I have a text file (Player_hits.text) that I am trying to pull player batting averages from. Similar to lines 179-189 I want to find an average. However, I do not want to find the average for the entire team. Instead, I want to find the average of every individual player on the team.

For instance, the text file is set up as such:
hit, name
[1, 'Riley']
[1, 'Alex']
In this file a 1 defines a hit and a 0 means the player did not get a hit. I am trying to pull an individual average for both players. (Alex = 0.500, Riley = 0.666)
If someone could help, that would be greatly appreciated!
Thanks!

Voters
RILEYSENFTEN
Comments
hotnewtop
Saml2020

For this, I'd suggest using JSON to store the data.
However, if you want, you can split the file by \n. Then spilt it again with , ' then remove the extra [ and '].
Using other methods such as ast.literal_eval() may also work.