
我有一個包含用戶名和密碼的 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")
uj5u.com熱心網友回復:
您的代碼中存在一些問題。
主要的是,如果您第一次遍歷 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 的密碼。
uj5u.com熱心網友回復:
我不確定您的問題是否已經解決。但我怎么理解,你只想要你reader_obj = csv.reader(file_obj)獨特的線條嗎?
dict()為什么不用key=username 和 value=pw填充?因此,您確保每個用戶名在您的字典中只出現一次,因此是不同的:
user_pw = dict()
reader_obj = csv.reader(file_obj)
for (user, pw) in reader_obj:
user_pw[user] = pw
uj5u.com熱心網友回復:
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511146.html
下一篇:如何匹配陣列和物件迭代器?
