首页 > 解决方案 > 从文本文件中检查密码并将结果打印到单独的文本文件中

问题描述

我对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

标签: pythonfilepasswords

解决方案


您的代码中有错误,您传递给 check pwd 函数的参数存在缩进问题,即使它确实有效,您也只会将最后一个密码写入文件

将您的代码更改为以下内容应该可以修复它

with open("passwdout.txt","w") as outfile:
    [outfile.write(checkpasw0rd(pswd)) for pswd in infile]

确保with statement您不再需要关闭 outfile,这是自动处理的

使用上面的代码替换你的整个 forloop


推荐阅读