【问题标题】:How to replace a list in a file?如何替换文件中的列表?
【发布时间】: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


【解决方案1】:

从文件中删除一行与重写文件减去匹配的行是一样的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2013-04-02
    • 2018-11-30
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多