简体   繁体   中英

How can i delete a couple lines of text that I inputted into a text file in python?

I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes. Im trying to create a function to delete an entry but im not sure how to make the function delete all the lines of information associated with the Username. I want an input asking "Which account to delete" you put the username, and it will delete all information associated with the username in info.txt

Code:

import os.path #Imports os module using path for file access


def checkExistence(): #Checking for existence of file
    if os.path.exists("info.txt"):
        pass #pass is used as a placeholder bc if no code is ran in an if statement and error comes.
    else:
        file = open("info.txt", "w") #creates file with name of info.txt and W for write access
        file.close()
    

def appendNew():
    #This function will append a new password in the txt file
    file = open("info.txt", "a") #Open info.txt use a for appending IMPORTANT: opening a file with w for write will write over all existing data
    

    userName = input("Enter username: ")
    print(userName)
    os.system('cls')
    password = input("Enter password: ")
    print(password)
    os.system('cls')
    website = input("Enter website: ")
    print(website)
    os.system('cls')

    print()
    print()

    usrnm = "Username: " + userName + "\n" #Makes the variable usrnm have a value of "Username: {our username}" and a new line
    pwd = "Password: " + password + "\n"
    web = "Website: " + website + "\n"

    file.write("----------------------------------\n")
    file.write(usrnm)
    file.write(pwd)
    file.write(web)
    file.write("----------------------------------\n")
    file.write("\n")
    file.close()

def readPasswords():
    file = open("info.txt", "r") #Open info.txt with r for read
    content = file.read() # Content is everything read from file variable (info.txt)
    file.close()
    print(content)





checkExistence()

while True:
    choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
    print(choice)
        


    if choice == "1":
        os.system('cls')
        appendNew()
    elif choice == "2":
        os.system('cls')
        readPasswords()
    elif choice == "3":
        os.system('cls')
    else:
        os.system('cls')
        print("huh? thats not an input.. Try again.\n")
    

I tried making a delete account function by deleting the line which matched the username. My only problem is that it only deletes the line in info.txt with the username, but not the password and website associated with that username.

Firstly, you're using the wrong tool for the problem. A good library to try is pandas , using .csv files (which one can think of as pore program oriented excel files). However, if you really want to use the text file based approach, your solution would look something like this:

with open(textfile, 'r+') as f:
    lines = [line.replace('\n', '') for line in f.readlines()]
    # The above makes a list of all lines in the file without \n char
    index = lines.index(username)
    # Find index of username in these lines
    for i in range(5):
        lines.pop(index)
    # Delete the next five lines - check your 'appendNew' function
    # you're using five lines to write each user's data
    print(lines)
    f.write("\n".join(lines))
    # Finally, write the lines back with the '\n' char we removed in line 2


# Here is your readymade function:

def removeName(username):
    with open("info.txt", 'r+') as f:
        lines = [line.replace('\n', '') for line in f.readlines()]
        try:
            index = lines.index(username)
        except ValueError:
            print("Username not in file!")
            return
        for i in range(5):
        lines.pop(index)
        print(lines)
        f.write("\n".join(lines))


# Function that also asks for username by itself

def removeName_2():
    username = input("Enter username to remove:\t")
    with open("info.txt", 'r+') as f:
        lines = [line.replace('\n', '') for line in f.readlines()]
        try:
            index = lines.index(username)
        except ValueError:
            print("Username not in file!")
            return
        for i in range(5):
        lines.pop(index)
        print(lines)
        f.write("\n".join(lines))


# Usage:
removeName(some_username_variable)
removeName_2()

Again, this is a rather clunky and error prone approach. If you ever change the format in which each user's details are stored, your would have to change the number of lines deleted in the for loop. Try pandas and csv files, they save a lot of time.

If you're uncomfortable with those or you're just starting to code, try the json library and .json files - at a high level they're simple ways of storing data into files and they can be parsed with the json library in a single line of code. You should be able to find plenty of advice online about pandas and json.

If you're unable to follow what the function does, try reading up on try-except blocks and function parameters (as well as maybe global variables).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM