2017-08-08 3 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

関連する問題