【发布时间】:2020-11-19 23:04:59
【问题描述】:
我有一个包含我的密码的文件,如下所示:
Service: x
Username: y
Password: z
我想写一个删除这些密码部分的方法。这个想法是,我可以搜索服务以及它被删除的部分。到目前为止代码有效(我可以说,因为如果你在我写删除部分的地方插入print(section) 它工作得很好),我只是不知道如何从文件中删除一些东西。
fileee = '/home/manos/Documents/python_testing/resources_py/pw.txt'
def delete_password():
file = open(fileee).read().splitlines()
search = input("\nEnter Service you want to delete: ")
if search == "":
print("\nSearch can't be blank!")
delete_password()
elif search == "cancel":
startup()
else:
pass
found = False
for index, line in enumerate(file):
if 'Service: ' in line and search in line:
password_section = file[index-1:index+3]
# delete password_section
found = True
if not found:
print("\nPassword for " + search + " was not found.")
delete_password()
【问题讨论】:
-
最简单的方法是重新写入文件,将除要删除的部分之外的所有内容都写入。
-
我该怎么做?
-
显然你知道如何读取文件;你知道怎么写文件吗?您已经编写了代码来确定要删除的部分。您能否编写代码来确定您要删除的部分是什么不是?应该很简单。 Stack Overflow 不是代码编写服务。
标签: python python-3.x file indexing enumerate