Search code examples
pythonprintingreturn

Return in python, reading values from .txt file


Level: beginner

Hey, i'm trying to resolve an exercise in Python.

The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".

If i use print a result is printed as expected, however if i use return, function always returns "-1", even if a userName exists in a file.

Looks like it reads only the first user, score values from the .txt file.

Can anybody please explain why "return" works that way in this case?

userScores.txt:

Ann, 100
Benny, 102
Carol, 214
Darren, 129

Code:

  try:
        def getUserPoint(userName):
            f = open("userScores.txt", "r")
            file = f.readlines()
            print(file)
            for item in file:
                print(item)
                content = item.split(',')
                if content[0] == userName:
                    f.close()
                    return content[1]
                    #print(content[1])
                else:
                    f.close()
                    return "-1"
                    #print("-1")
    except IOError:
        print("File not found")
        f = open("userScores.txt", "w")
        f.close()
        print("-1")

Solution

  • You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:

    def getUserPoint(userName):
        try:
            with open("userScores.txt", "r") as file:
                for item in file:
                    print(item)
                    content = item.split(',')
                    if content[0] == userName:
                        return content[1]
                return "-1"
        except IOError:
            print("File not found")
            return "-1"