仅查找CSV文件中的第一个匹配项

j2datikz  于 2023-01-15  发布在  其他
关注(0)|答案(3)|浏览(139)

我有一个脚本,它读取一个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的好友请求"

bq3bfh9z

bq3bfh9z1#

将结果存储在变量中:

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
ntjbwcob

ntjbwcob2#

你可以试试这个:

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

fdbelqdn3#

对于如此琐碎的事情,您不需要 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'))

相关问题