Here from the text of the file I wanted to print the details of the footballer

Question:

Here from the text of the file I wanted to print the details of the footballer

from re import findall
f = open('soccer_player.txt', "r")
mathces = 0
textin = f.readlines()
for line in textin:
    mathces= int(('').join(findall(r'd+', line)))
    if(mathces>50)
        print (mathces)
f.close()

How to do?

This is the txt file:

Brad Ebert,47
Brodie Smith,46
Kade Simpson,46
Luke Shuey,46
Justin Westhoff,46
Nic Naitanui,46
Chad Wingard,462
Jordan Lewis,459
Michael Johnson,459
Hamish Hartlett,458
Steven Motlop,457
Jaeger O'Meara,457
Asked By: longwild laptop

||

Answers:

Though your question is not clear, may be you want to do one of the following:

  1. Printing the value (may be a score) which is greater than 50. Your code may not work due to syntax error after if statement. Correct way will be:
from re import findall
f = open('soccer_player.txt', "r")
mathces = 0
textin = f.readlines()
for line in textin:
    mathces= int(('').join(findall(r'd+', line)))
    if(mathces>50):
        print (mathces)
f.close()

Output will be:

462
459
459
458
457
457
  1. Printing the player name who has a score greater than 50. Correct way will be:
f = open('soccer_player.txt', "r")
mathces = 0
textin = f.readlines()
for line in textin:
    player, score = line.split(',')
    if (int(score) > 50):
        print(f"{player} ({int(score)})")
f.close()

Output will be:

Chad Wingard (462)
Jordan Lewis (459)
Michael Johnson (459)
Hamish Hartlett (458)
Steven Motlop (457)
Jaeger O'Meara (457)

Hope this will help.

Answered By: Debonil Ghosh

Improving upon @Debonil Ghosh, instead of using:

f = open('soccer_player.txt', "r")
f.close()

This is a common bad practice, and python has a better solution for opening and readind files. We can use:

with open('soccer_player.txt') as f:
    mathces = 0
    textin = f.readlines()
    for line in textin:
        player, score = line.split(',')
    if (int(score) > 50):
        print(f"{player} ({int(score)})") 

We can remove the "r" as reading is the default mode when using with open. We also do not need to close the file as this is automatically handled

Answered By: PythonProgrammer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.