如何替换文件中的列表?
How to replace a list in a file?
我有一个包含我的密码的文件,如下所示:
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()
从文件中删除一行等同于重写文件减去该匹配行。
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)
我有一个包含我的密码的文件,如下所示:
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()
从文件中删除一行等同于重写文件减去该匹配行。
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)