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’
>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