简体   繁体   English

如何删除我在 python 中输入到文本文件中的几行文本?

[英]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.我正在 python 中制作一个简单的小型密码管理器。我具有创建一个帐户的功能,该帐户具有 3 个输入、用户名、密码和网站。 I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes.我有一个 function 可以查看所有帐户,其中显示了所有信息所在的文件 info.txt 的内容。 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.我试图创建一个 function 来删除一个条目,但我不确定如何让 function 删除与用户名关联的所有信息行。 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我想要一个输入询问“要删除哪个帐户”你输入用户名,它会删除 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.我尝试通过删除与用户名匹配的行来删除帐户 function。 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.我唯一的问题是它只删除了 info.txt 中带有用户名的行,但没有删除与该用户名关联的密码和网站。

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).pandas是一个不错的尝试库,它使用.csv文件(可以将其视为面向孔隙程序的 excel 文件)。 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.如果您更改了每个用户详细信息的存储格式,则必须更改for循环中删除的行数。 Try pandas and csv files, they save a lot of time.尝试 pandas 和 csv 文件,它们节省了大量时间。

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.如果您对这些感到不舒服或者您刚刚开始编码,请尝试 json 库和.json文件 - 在高层次上,它们是将数据存储到文件中的简单方法,并且可以使用json库在一个单行代码。 You should be able to find plenty of advice online about pandas and json.您应该能够在网上找到很多关于 pandas 和 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).如果您无法理解 function 的作用,请尝试阅读try-except块和 function 参数(以及可能的全局变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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