[英]How can i delete a couple lines of text that I inputted into a text file in python?
我正在 python 中制作一个简单的小型密码管理器。我具有创建一个帐户的功能,该帐户具有 3 个输入、用户名、密码和网站。 我有一个 function 可以查看所有帐户,其中显示了所有信息所在的文件 info.txt 的内容。 我试图创建一个 function 来删除一个条目,但我不确定如何让 function 删除与用户名关联的所有信息行。 我想要一个输入询问“要删除哪个帐户”你输入用户名,它会删除 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 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")
我尝试通过删除与用户名匹配的行来删除帐户 function。 我唯一的问题是它只删除了 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 的建议。
如果您无法理解 function 的作用,请尝试阅读try-except
块和 function 参数(以及可能的全局变量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.