0

I am new here and new to Programming too. I am reading Jamie Chan's Learn Python in One Day and am currently at the Practical Project section. I am trying to make python read a line from a txt file. The txt file contains a name and a number seperated by a comma, This is the text file

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

I succeded in making it read the first line but the trying to print the second line by calling on the name there keeps returning a nill. When I switch the lines, the same thing occurs, it reads the name in the first line but returns nill on the name in the second file. This is the function I tried to use to read the texts:

def getUserPoint(userName):
    f = open('userScores.txt', 'r')
    for line in f:
        result = line.splitlines()
        if userName in line:
            return result
        else:
            return "nill"
    f.close()


s = getUserPoint(input('Ann'))
print(s)

And this is the result:

nill

and this is the instructions: Each line records the information of one user. The first value is the user’s username and the second is the user’s score. Next, the function reads the file line by line using a for loop. Each line is then split using the split() function Let’s store the results of the split() function in the list content. Next, the function checks if any of the lines has the same username as the value that is passed in as the parameter. If there is, the function closes the file and returns the score beside that username. If there isn’t, the function closes the file and returns the string ‘-1’

Am terribly sorry for the long winded post.

  • 1
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – whackamadoodle3000 Oct 21 '20 at 15:55
  • 1
    I've always wondered how good these "Learn X in One Day and Learn It Well" books are. IME you can have one or the other, but not both. Jumping into coding without learning the basics first is a recipe for disaster because you the emphasis is on churning out code for example problems without any thought to building a strong foundation and the logical thinking that is needed to write and debug programs effectively. For example, it's _essential_ to know [how to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) and these books seldom teach you that. – Pranav Hosangadi Oct 21 '20 at 16:00

4 Answers4

1

you can use :

def getUserPoint(userName):
  f = open('userScores.txt', 'r')
  for line in f.readlines():
    result = line.splitlines()
    if userName in line:
        f.close()
        return result
  
  f.close()
  return "nill"
  


s = getUserPoint(input('Ann'))
print(s)
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
NHL
  • 277
  • 1
  • 6
  • Welcome to Stack Overflow! Please take the [tour] and read [answer]. While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From [answer]: _"Brevity is acceptable, but fuller explanations are better."_ – Pranav Hosangadi Oct 21 '20 at 15:56
  • Nothing is wrong with `for line in f` since files are iterable – OneCricketeer Oct 21 '20 at 15:56
  • you can try now, you need to remove the return "nill" from the loop – NHL Oct 21 '20 at 15:58
  • Thanks for the tip – ShadoWalker Oct 21 '20 at 16:11
1

One problem is that you have an else statement that is matched and will immediately end the function and loop

You need to return the default result after you've looked at all lines

def getUserPoint(userName):
    with open('userScores.txt') as f:
        for line in f:
            if userName == line.rstrip().split(',')[0]:
                return line
    return "nill"

Then, as shown, you either want to split the comma and check the first column, or userName in line . Otherwise, you are checking

'Ann' in ["Ann, 100", ""]

since splitlines() will split at the newline character at the end, which returns False

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

See below

The code takes care of closing the file.

It will return None if no match found, else 'user point' is returned

def get_user_point(user_name):
    with open('userScores.txt', 'r') as f:
      lines = [l.strip() for l in f]
      for line in lines:
        parts = line.split(',')
        if user_name == parts[0]:
          return parts[1]
balderman
  • 22,927
  • 7
  • 34
  • 52
0

Thanks everyone for the help... This code by OneCricketeer worked:

def getUserPoint(userName):
    with open('userScores.txt') as f:
        for line in f:
            if userName == line.split(',')[0]:
                return line
    return "nill"

Since am new to Python and programming in General, I will probably be asking a lot more questions. Thanks for the help everyone.