Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Only finding first match in CSV file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading