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



我正在制作一个简单的python密码管理器。我有创建一个帐户,其中有3个输入,用户名,密码和网站的功能。我有一个功能来查看所有的帐户,其中显示文件的内容info.txt所有的信息去。我试图创建一个函数来删除一个条目,但我不确定如何使该函数删除与用户名关联的所有信息行。我想要一个输入询问"要删除哪个帐户"。输入用户名,它会删除info.txt

中与用户名相关的所有信息代码:

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 accountn 2. View accountsn 3. Delete accountn")
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")

我尝试通过删除与用户名匹配的行来创建删除帐户功能。我唯一的问题是它只删除info.txt中包含用户名的行,而不删除与该用户名关联的密码和网站。

首先,您使用了错误的工具来解决问题。可以尝试的一个很好的库是pandas,它使用.csv文件(可以将其视为面向孔隙程序的excel文件)。但是,如果您真的想使用基于文本文件的方法,那么您的解决方案应该是这样的:

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

同样,这是一种相当笨拙且容易出错的方法。如果更改存储每个用户详细信息的格式,则必须更改for循环中删除的行数。可以试试pandas和csv文件,它们可以节省很多时间。

如果你对那些不舒服,或者你刚刚开始编码,尝试json库和.json文件-在高层次上,他们是简单的方式将数据存储到文件中,他们可以用json库在一行代码中进行解析。你应该可以在网上找到很多关于pandas和json的建议。

如果你不能跟随函数做什么,试着阅读try-except块和函数参数(以及全局变量)。

最新更新