Python 将密码保存在.txt文件中,以便以后替换(如果已存在)
我需要将密码保存到.txt文件并运行该程序。如果该用户的密码已经存在,我将询问是否要替换它Python 将密码保存在.txt文件中,以便以后替换(如果已存在),python,Python,我需要将密码保存到.txt文件并运行该程序。如果该用户的密码已经存在,我将询问是否要替换它 import string def registo(): found = False with open("Accounts.txt", "r+") as file: for line in file: user, pw = line.split(":") if number == user:
import string
def registo():
found = False
with open("Accounts.txt", "r+") as file:
for line in file:
user, pw = line.split(":")
if number == user:
print("User already exists")
found = True
file.close()
while found == True:
changepw = input("Change user password?[s/n]")
if changepw == "s":
newpw = input("Insert new password")
s = open("Accounts.txt").read()
s = s.replace(number,'%s:%s\n'%(number,newpw))
f = open("Accounts.txt", "w")
f.write(s)
f.close()
if not found:
with open("Accounts.txt", "a+") as file:
account = '%s:%s\n'%(numeroaluno,password)
file.write(account)
print ('Saved!')
number = input("Insert username")
password = input("Insert password")
registo()
我希望输出一行并替换密码,例如username:password
我在.txt文件中得到以下输出:
8180324:flavio #The actually user
:pedroooo #When i try to replace the password of the first user
81803123:pedrooooo #Another user
但是我想替换该行,而不是添加另一行…您的代码出现了一些问题,我尝试快速修复它。我认为您需要的是以下内容(当然,您不应该首先将密码保存为纯文本)
@TrebledJ代码工作,但不是我想要的方式…嘿,欢迎来到SO!你能给我们看一下你的档案吗?另外,请将代码中的信息(如
打印
和输入
)翻译成英语。作为一个说葡萄牙语的人,我可以很容易地理解它,但我担心对一个不熟悉葡萄牙语的人来说,这不会那么容易;)@mfx28这很模糊。寻求调试帮助的问题(“此代码为什么不工作?”)必须包括所需的行为、问题本身中的特定问题或错误。没有明确问题陈述的问题对其他读者没有用处。@HelenaMartins感谢您提供的提示,已经做到了……好吧,替换实际上起了作用,但现在我不能只添加一个用户,我遇到了以下错误:回溯(最近一次调用):文件“C:\Users\pedro\Desktop\steste\teste.py”,第35行,在注册表中(用户名,newpw)文件“C:\Users\pedro\Desktop\steste\teste.py”,第28行,在注册表帐户=“%s:%s\n%”(用户名,newpw)UnboundLocalError:分配前引用了局部变量“newpw”
import fileinput
import string
def registo(username, password):
found = False
with open("Accounts.txt", "r+") as file:
for line in file:
user, pw = line.split(":")
if username == user:
print("User already exists")
found = True
file.close()
if found == True:
changepw = input("Change user password?[s/n]")
if changepw == "s":
output = ""
for line in fileinput.input(["Accounts.txt"], inplace=True):
if line.strip().startswith(username):
line = username+":"+newpw
output = output + line
f = open("Accounts.txt", "w")
f.write(output)
f.close()
if not found:
with open("Accounts.txt", "a+") as file:
account = '%s:%s\n'%(username,newpw)
file.write(account)
print ('Conta Guardada')
username = input("Insert username")
newpw = input("Insert password")
registo(username, newpw)