Return in python, reading values from .txt file

python read text file line by line
python write to text file
python read and write to same file
python write variable to file
python read text file into string
python read local file
python write text file line by line
read 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")

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"

7. Input and Output, When you use the open function, it returns something called a file object. An argument is nothing more than a value that has been provided to a There are actually a number of ways to read a text file in Python, not just one. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file.

On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.

E.g. If you call getUserPoint('Benny')

On the first iteration of the loop, it will compare "Ann" == "Benny"

This returns false, so the control goes to your else clause and return from the function - no more looping.

Reading and Writing Files in Python, There are three ways to read data from a text file. read() : Returns the read bytes in form of a string. readline() : Reads a line of the file and returns in form of a string. readlines() : Reads all the lines and return them as each line a string element in a list. A Python program can read a text file using the built-in open() function. For example, below is a Python 3 program that opens lorem.txt for reading in text mode, reads the contents into a string variable named contents, closes the file, and then prints the data.

import os

def getUserPoint(userName):
    f=open('userScores.txt')
    file=f.readlines()
    for item in file:

        content=item.split(',')

        if content[0]==userName:
            f.close()
            return content[1]
        else:
            continue

    f.close()   
    print('UserNotfound')
    return '-1'

x=getUserPoint('Benny')
print(x)

Reading and Writing to text files in Python, The str() function is meant to return representations of values which are fairly Normally, files are opened in text mode, that means, you read and write strings  python,python-2.7,python-3.x. The functions are returning tuples, because return only gives back one item. You can "unpack" the tuple returned by prepending it with an asterisk. The syntax will look like this: print function1(*function2(1,2))

7. Input and Output, The str() function is meant to return representations of values which in text files are automatically altered slightly when data is read or written. Overview When you’re working with Python, you don’t need to import a library in order to read and write files. It’s handled natively in the language, albeit in a unique manner. The first thing you’ll need to do is use Python’s built-in open function to get a file object. The open function opens a file. […]

7. Input and Output, The open function returns a file object that contains methods and attributes With Python you can create a .text files (guru99.txt) by using the code, we You can also read your .txt file line by line if your data is too big to read. Python file method read() reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes. Syntax. Following is the syntax for read() method − fileObject.read( size ); Parameters. size − This is the number of bytes to be read from the file. Return Value. This method returns the

Python File Handling: Create, Open, Append, Read, Write, At its core, a file is a contiguous set of bytes used to store data. This data is out there. For this tutorial, you'll only deal with .txt or .csv file extensions. With these types of files, open() will return a TextIOWrapper file object: >>> >>> file  in python I am trying to read data values from a .txt file but am having problems. There are object V objects indexed from $0,1,2,,|V|-1$ and each has a profit(p) and weight(w). Attached is the .txt file I am trying to read and store in appropriately titles vectors $\vec{p}$ and $\vec{w}$. For example the lines of the .txt file are. param n

Comments
  • You should use try inside the function, instead of defining the function inside of it.
  • Got it! Thanks for explanation