Only finding first match in CSV file

Question:

I have a script that reads a CSV file ‘friends_req.csv’ and checks if a specific user exists in the file. If the user exists, it prints "You have friend request", otherwise it prints "No request found for this user". However, when there are multiple requests for the same user, the script only prints the first request but not the others. I need to print all requests on separate lines. But I don’t know how to make it.

This is my code

def get_request(user):
    if not os.path.exists('friends_req.csv'):
        open('friends_req.csv','w').close()
    with open('friends_req.csv','r+') as d:
        reader = csv.reader(d)
        for row in reader:
            if row[1] == user:
                print(f'You have a friend request from {row[0]}')
                return row[0]
    print("No request found for this user")

And this is my CSV file

u,user
g,user

It only prints ‘you have friend request from u’, but it must print ‘you have friend request from u’ and on another line ‘you have friend request from g’

Asked By: estakkk

||

Answers:

Store results in a variable:

def get_request(user):
    with open('friends_req.csv') as d:
        reader = csv.reader(d)
        results = [row[0] for row in reader if row[1] == user]
        if results:
            print(f'You have friends request from {", ".join(results)}')
        else:
            print("No request found for this user")
        return results

Output:

>>> res = get_request('user')
You have friends request from u, g

>>> res
['u', 'g']

friends_req.csv:

u,user
g,user
Answered By: Corralien

You can try this :

def get_request(user):
    if not os.path.exists('friends_req.csv'):
        open('friends_req.csv','w').close()
    requests = []
    with open('friends_req.csv','r+') as d:
        reader = csv.reader(d)
        for row in reader:
            if row[1] == user:
                requests.append(row[0])
    if len(requests) > 0:
        for request in requests:
            print(f'You have a friend request from {request}')
    else:
        print("No request found for this user")
Answered By: Othman_belmouzouna

You don’t need the csv module for something so trivial. Just do this:

FILENAME = 'friends_req.csv'

def get_request(filename, user):
    requests = []
    try:
        with open(filename) as data:
            for line in map(str.strip, data):
                f, u = line.split(',')
                if u == user:
                    requests.append(f)
    except FileNotFoundError:
        pass
    return requests

print(get_request(FILENAME, 'user'))
Answered By: Fred
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.