我正在尝试创建一个程序,用户可以在其中添加用户名和密码到文本文件,然后删除文本文件中的用户名和密码。目前我不知道如何删除一行代码并保留相同的文本文件,删除它的唯一方法是让用户输入他们想要删除的用户名,然后删除密码和用户名。到目前为止我的代码:(在此代码中,我已经使用户名和密码检查功能正常工作。)感谢您的帮助:)
import re
def UsernameChecking():
print("\nYour Username must have no blank spaces and must be less than 20 characters long")
ab = False
while not (ab):
global Username
Username = input("Please enter what you would like your username to be:\n")
if len(Username) > 20:
print("You username must be under 20 characters long")
elif re.search('[ ]',Username):
print("There is not allowed to be any blank spaces in your username")
else:
print("Your username has been accepted!")
ab = True
def PasswordChecking():
print("\nYour password must be at least 6 characters. \nIt also must be 12 or less characters")
ac = False
while not (ac):
global Password
Password = input("Please enter what you would like your password to be:\n")
if len(Password) < 6:
print("Your password must be 6 or more characters long")
elif len(Password) > 12:
print("Your password must be 12 or less characters long")
else:
print("Your password has been accepted!")
ac = True
def CreateFile():
f = open("UsernameDatabase.txt","w")
f.close()
def AddingData():
f = open("UsernameDatabase.txt", "a")
f.write("\n\nUsername:" + (Username))
f.write("\nPassword:" + (Password))
f.close()#closes the file
def DeletingData():
DeleteRequest = input("What Username and password would you like to delete. PLease enter the username:\n")
f = open("UsernameDatabase.txt", "r+")
def RunningProgram():
zz = False
while not (zz):
Q = input("Do you want to add a username and password to the file?\n")
if Q == "Y":
UsernameChecking()
PasswordChecking()
AddingData()
else:
zz = True
RunningProgram()
DeletingData()
答案 0 :(得分:0)
从文件中删除用户名和密码:
data = [i.strip("\n").split(":") for i in open("UsernameDatabase.txt")]
user_name_to_delete = "something"
password_to_delete = "something"
f = open('UsernameDatabase.txt', 'w')
for entry in data:
if entry[-1] != user_name_to_delete or entry[-1] != password_to_delete:
f.write(':'.join(entry)+'\n')
f.close()