我是python的新手,实际上非常新。我有一个作业,我要检查文本文件中的密码列表,通过一个函数运行它,以确保每个密码都符合必要的条件,然后将结果打印在新的文本文件中。我没有使用密码功能,但为了我的一生,我不知道如何将结果打印在新的文本文件上。希望有人可以帮助我朝正确的方向
infile = open("passwdin-1.txt","r")
psswd = infile.readline()
outfile = open("passwdout.txt","w")
for pswd in infile:
resultpsswd = checkPassw0rd(psswd)
outfile.write(resultpsswd)
infile.close()
outfile.close()
def checkPassw0rd(psswd):
countLength = len(psswd)
countUC = 0
countLC = 0
countDigit = 0
specialCH = 0
resultpsswd = psswd
for ch in psswd:
if ch.isupper():
countUC += 1
elif ch.islower():
countLC += 1
elif ch.isdigit():
countDigit += 1
elif ch in "!$%":
specialCH = 0
if countLength >= 6 and countUC > 0 and countLC >= 2 and countDigit > 0 and specialCH > 0:
return True, resultpsswd "Password is valid and accepted"
else:
resultpsswd == "Password is invalid and not accepted"
if countLength < 6:
resultpsswd == resultpsswd + "\n Password has to be at least 6 characters long. "
if countUC == 0:
resultpsswd == resultpsswd + "\n Password has to have at least one upper case character. "
if countLC == 0:
resultpsswd == resultpsswd + "\n Password has to have at least one lower case character. "
if countDigit == 0:
resultpsswd == resultpsswd + "\n Password has to have at least one digit. "
if specialCH == 0:
resultpsswd == resultpsswd + "n\ Password has to have at least one of the special charaters '!$%'. "
return False, resultpsswd
答案 0 :(得分:0)
您的代码中有一个错字,您传递给check pwd函数的参数存在缩进问题,即使它确实起作用,您也只会将最后一个密码写入文件
将您的代码更改为类似于以下内容的代码应该可以解决
with open("passwdout.txt","w") as outfile:
[outfile.write(checkpasw0rd(pswd)) for pswd in infile]
with statement
确保您不再需要关闭输出文件,这是自动处理的
使用上面的代码替换整个forloop
答案 1 :(得分:0)
让我尝试总结一下使示例工作可行的方法。
for pswd in infile:
resultpsswd = checkPassw0rd(psswd)
您应该将pswd
传递给checkPassw0rd
函数您的checkPassw0rd
函数的输出是一个元组(,resultpsswd),因此您只应考虑该元组的第二项:
okNok, resultpsswd = checkPassw0rd(psswd)
outfile.write(resultpsswd)
outfile.write(resultpsswd)
行。最后类似的事情应该起作用:
infile = open("passwdin-1.txt","r")
psswd = infile.readline()
infile.close()
#outfile = open("passwdout.txt","w") --> Better to use the with statement
with open("passwdout.txt", "w") as outfile:
for pswd in infile:
okNok, resultpsswd = checkPassw0rd(pswd)
outfile.write(resultpsswd)
#No need to explicitly close the file, the with statement will do it
我希望这会有所帮助。