只在CSV文件中查找第一个匹配项



我有一个脚本,读取CSV文件'friends_req.csv'并检查该文件中是否存在特定的用户。如果用户存在,则打印"您有好友请求",否则打印"未找到此用户的请求"。但是,当同一用户有多个请求时,脚本只打印第一个请求,而不打印其他请求。我需要在单独的行上打印所有请求。但是我不知道怎么做。

这是我的代码

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")
这是我的CSV文件
u,user
g,user

它只打印'你有来自u的朋友请求',但它必须打印'你有来自u的朋友请求'和另一行'你有来自g的朋友请求'

将结果存储在变量中:

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

输出:

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

friends_req.csv:

u,user
g,user

你可以试试:

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")

对于如此琐碎的事情,您不需要csv模块。只需这样做:

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'))

相关内容

  • 没有找到相关文章

最新更新