简体   繁体   中英

Python: How to return specific lines from a text

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.

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)

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

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM