2017-08-08 46 views
1

我想製作一個程序,用戶可以將用戶名和密碼添加到文本文件,然後刪除文本文件中的用戶名和密碼。目前我不知道如何刪除一行代碼並保留相同的文本文件,並且刪除它的唯一方法是讓用戶輸入他們想要刪除的用戶名,然後刪除密碼和用戶名。到目前爲止我的代碼(在這個代碼中,我已經取得了用戶名和密碼檢查功能的工作。)感謝您的幫助:)找到文本文件中的特定字符串,然後刪除

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

從文件中刪除用戶名和密碼:

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() 
+0

當我用這段代碼運行它時,它會刪除所有用戶名,而不僅僅是我想要刪除的用戶名。 – Matt

+0

@Matt你可以發佈一個輸入文件的樣本嗎? – Ajax1234

+0

@ Ajaz1234別擔心我想我已經修好了 – Matt

相關問題