I have a csv file with usernames and passwords. In the file, there can be more than one row having the same username and password. In my code, I created a list of usernames who have strong passwords so now what I want is to iterate through all the csv file and if the username and password in my list matches the one in the file I'll print "Strong Password" else, I'll print "Weak Password".
I did it in my code in a very long way, so I was asking if there is a faster way to do so.
Here is my code:
#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")
CodePudding user response:
There are a couple of problems in your code as it is.
The main one is that, if you iterate over the rows in the csv file the first time (for row in reader_obj), the next time you will do it (for the new user/password) the csv file will still be at the end, so nothing will happen.
Without changing your logic too much, this works:
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.")
The problem is that, this way, you'll see more entries corresponding to the same user_ID. This can be fixed, but depends on what you want, considering you do have multiple entries in the .csv file as well.
Anyway, you could do something like:
# 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])
which prevents the code form checking the same user_id's password multiple times.
CodePudding user response:
I'm not sure if your problem is already solved. But how i understand it, you only want the lines in your reader_obj = csv.reader(file_obj)
distinct?
Why not filling a dict()
with key=username and value=pw? therefore you make sure every username is only present once in your dict, therefore distinct:
user_pw = dict()
reader_obj = csv.reader(file_obj)
for (user, pw) in reader_obj:
user_pw[user] = pw
CodePudding user response:
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")