Search code examples
pythonpython-3.xfileindexingenumerate

How to replace a list in a file?


I have a file which contains my passwords like this:


Service: x
Username: y
Password: z

I want to write a method which deletes one of these password sections. The idea is, that I can search for a service and the section it gets deleted. So far the code works (I can tell because if you insert print(section) where I wrote delete section it works just fine), I just don't know how to delete something from the file.

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

Solution

  • Deleting a line from the file is the same as re-writing the file minus that matching line.

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