如何使用python检查csv文件中存在的多个值

5hcedyr0  于 2022-12-06  发布在  Python
关注(0)|答案(3)|浏览(163)

我有一个包含用户名和密码的csv文件。在文件中,可以有多行具有相同的用户名和密码。在我的代码中,我创建了一个具有强密码的用户名列表,所以现在我想要遍历所有csv文件,如果列表中的用户名和密码与文件中的用户名和密码匹配,我将打印“强密码”,否则,我将打印“弱密码”。
我在我的代码中做了很长一段时间,所以我问是否有一个更快的方法这样做。
下面是我的代码:

#list of usernames and pwds which are strong
username_pwd=[["u002","12345"],["u003","123456"],["u004","1234567"]]
#read the csv file
reader_obj = csv.reader(file_obj)

for item in username_pwd:
    for row in reader_obj:
         if all(value in row for value in item):
             print("Strong PWD")
ohtdti5x

ohtdti5x1#

在您的代码中存在一些问题。
主要的一点是,如果你第一次迭代csv文件中的行(针对reader_obj中的行),那么下次你再这样做(针对新用户/密码)时,csv文件仍然在末尾,所以什么也不会发生。
在不过多更改逻辑的情况下,可以这样做:

import csv

# list of usernames and pwds which are strong
username_pwd = [["u002", "12345"], ["u003", "123456"], ["u004", "1234567"]]

# to read the csv file, you need to create a file object first (csv_file)
with open("passwords.csv") as csv_file:
    # then, you can use this file object and read it
    reader_obj = csv.reader(csv_file)

    # go through the lines in the csv file once, and check if that line is in your list of strong passwords
    for row in reader_obj:
        if row in username_pwd:
            print(f"User_ID {row[0]} has a strong password.")
        else:
            print(f"User_ID {row[0]} has a weak password.")

问题是,这样一来,您将看到更多的条目对应于同一个user_ID。这是可以修复的,但取决于您的需要,考虑到您在.csv文件中也有多个条目。
总之,你可以这样做:

# go through the lines in the csv file once, and check if that line is in your list of strong passwords
already_done = []
for row in reader_obj:
    if row[0] not in already_done:
        if row in username_pwd:
            print(f"User_ID {row[0]} has a strong password.")
        else:
            print(f"User_ID {row[0]} has a weak password.")
        already_done.append(row[0])

这可以防止代码多次检查同一user_id的密码。

k2fxgqgv

k2fxgqgv2#

我不确定你的问题是否已经解决了。但是我的理解是,你只希望你的reader_obj = csv.reader(file_obj)中的行是不同的?
为什么不用key=username和value=pw来填充dict()呢?因此,您要确保每个用户名在dict中只出现一次,因此是不同的:

user_pw = dict()
reader_obj = csv.reader(file_obj)
for (user, pw) in reader_obj:
   user_pw[user] = pw
py49o6xq

py49o6xq3#

import pandas as pd 
df = pd.read_csv("file_path") 

filter = data["pwd"].isin(["xyz"])
if len(filter) > 1:
    print("strong password")
else:
    print("weak password")

相关问题