python - 从文本文件中检查密码并将结果打印到单独的文本文件中
问题描述
我对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
解决方案
您的代码中有错误,您传递给 check pwd 函数的参数存在缩进问题,即使它确实有效,您也只会将最后一个密码写入文件
将您的代码更改为以下内容应该可以修复它
with open("passwdout.txt","w") as outfile:
[outfile.write(checkpasw0rd(pswd)) for pswd in infile]
确保with statement
您不再需要关闭 outfile,这是自动处理的
使用上面的代码替换你的整个 forloop
推荐阅读
- reactjs - @aws-amplify 版本的 aws-amplify-react 连接
- javascript - 基本 jquery toggleClass 在 es6 类中不起作用
- python - 我的 IEEE-754 表示任何双精度浮点值的代码有问题
- mysql - 如果字符串不匹配sql如何返回0
- r - GSub 删除第一个数字之前的所有字符
- r - 在 Rstudio 中将两个分类变量合并为一个
- excel - 在VBA中的列底部粘贴原始数据
- r - 有没有办法报告导入数据集的文件名?
- vue.js - 如何在 Laravel 8 中安装 Vue.js
- c# - 何时以及为何在 C# 中使用“ValueObject”基类(来自 Microsoft Docs)?