我对python编程还很陌生,在完成了一系列初学者培训后,我想获得一些实际经验。
我的想法是开发一个帐户/密码分发工具。
它应该做的是:
- 导入带有帐户、用户和权限的csv(用户名1、帐户1-PasswordPart1、帐户2-PasswordPart2(
- 遍历accounts.csv(生成pw并将其附加到account对象(
- 遍历users.csv(为每个用户生成带有*.txt的加密zip,其中包含基于permissions.csv的帐户和一半密码(
1.导入
导入相当容易实现。
2.生成密码
这是我用来生成密码的功能:
def pw_generator(length):
#define data
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
#string.ascii_letters
#combine the data
all = lower + upper + num + symbols
#use random
randompw = random.sample(all,length)
#create the password
password = "".join(randompw)
#print the password
return password
3.使用accounts.csv并用它创建一个对象
这是我目前被卡住的地方。我试过这个。。(和许多其他方法(
class account:
def __init__(self,accountname,password):
self.accountname = accountname
self.password = password
acc_list = []
with open('accounts.csv', newline='') as csv_file:
reader = csv.reader(csv_file)
next(reader, None) # Skip the header.
for accountname, password in reader:
acc_list.append(account(account, password))
account.password=pw_generator(16)
print(accountname, account.password)
这给了我一个帐户名和密码的列表,但我不知道以后如何将它们用作数组。。
有什么想法吗?
谢谢!
首先,您为类指定了一个小写名称,从而为自己挖了一个坑。
这个东西:
acc_list.append(account(account, password))
如果您将class account
重命名为class Account
并重构代码,您会发现它没有任何意义:
acc_list.append(Account(Account, password))
通过将类Account
作为accountname
来创建类Account
的实例。这似乎不是你想做的事。
然后您还更改了一个未声明的类属性(不是实例属性,而是类属性!(:
Account.password=pw_generator(16)
委婉地说,这看起来也非常可疑。
其次,字段password
最终应该是什么并不明显。它是您从.csv
中读取的值吗?还是一些自动生成的pw?
你可能想做这样的事情:
for accountname, password in reader:
acc_instance = Account(accountname, password) # Create an instance
acc_list.append(acc_instance) # add the instance to the list
print(acc_instance.accountname, acc_instance.password) # print the instance
# Then you can do whatever you like with the list.
# For example you could redefine all passwords in all accounts and print new credentials:
for acc in acc_list:
acc.password = pw_generator(16)
print(acc.accountname, acc.password)
# Or save this list in whatever form you like.