简体   繁体   中英

how to delete line from text file in python

Hi fellow programmers,

I have a question

i wrote a code in python where we register a safe to people with a password

in the menu you have 4 options

the first option is to see how much safes there are left (1 to 12) the second option is to get a safe if all the 12 safes are in use python will reply with 'there are no safes left' if there is a safe available there will be applied a random safe number and you can add your password to it with the third option you can open your safe

with the fourth option you can delete your safe if you dont want to use it anymore and here i am stuck with my code i dont know how to ONLY delete the line where the safe is and after it is deleted the lines under it need to move up so that there are no empty spaces left.

to delete your safe the user needs to input his number and then his password if those match with the line in the textfile option 4 needs to only delete that line.

can someone help me please.

def kluis_teruggeven(): is the line where the fourth option code is

the textfile has


2;peter
3;johan
6;piet
7;cheese

my python code:

import random
create_bestand = open('fa_kluizen.txt')
bestand = open('fa_kluizen.txt', 'r')
line = bestand.readlines()
bestand.close

def main():
    while True:
        menu = input("""    
        Welkom bij het menu!    
        1: Ik wil weten hoeveel kluizen nog vrij zijn 
        2: Ik wil een nieuwe kluis 
        3: Ik wil even iets uit mijn kluis halen 
        4: Ik geef mijn kluis terug   
        5: ik wil stoppen   

        Maak je keuze van 1/5: """)

        if menu == '1':
            toon_aantal_kluizen_vrij()
        elif menu == '2':
            nieuwe_kluis()
        elif menu == '3':
            kluis_openen()
        elif menu == '4':
            kluis_teruggeven()
        elif menu == '5':
            break
        else:
            print("Je kan alleen de nummers 1,2,3,4,5 selecteren\nprobeer opnieuw")
            print(type(main))

def toon_aantal_kluizen_vrij():
    available_safe = 12 - len(line)
    print(f'er zijn nog {available_safe} kluizen vrij ')
    return  available_safe

def nieuwe_kluis():
    safenumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    file = open('fa_kluizen.txt', 'r')
    safes = file.readlines()
    for safe in safes:
        safe_split = safe.split(";")
        for safenumber in safe_split:
            if safenumber in safenumbers:
                safenumbers.remove(safenumber)
    if len(safenumbers) > 0:
        safe_number = random.choice(safenumbers)
        print(f'u heeft kluisnummer {safe_number} gekregen')
        password = input('voer een wachtwoord in voor uw kluis: ')
        appendsafe = open('fa_kluizen.txt', 'a')
        appendsafe.write(f'\n{safe_number};{password}')
        appendsafe.close()
        print(f'uw Kluis is {safe_number} toegewezen!')
    else:
        print('Alle kluizen zijn al gebruikt.')
    file.close()

def kluis_openen():
    while True:
        file = open('fa_kluizen.txt', 'r')
        safes = file.readlines()
        safenumber = input('voer uw kluisnummer hier in: ')
        password = input('voer uw wachtwoord van uw kluis hier in: ')
        safenumbercode = safenumber+';'+password
        for safe in safes:
            safe = safe.strip()
            if safenumbercode == safe:
                numbercode = True
                break
            else:
                numbercode = False
        if numbercode == True:
            print('Kluis is geopend')
            break
        else:
            print('De kluisnummer en/of wachtwoord is onjuist, probeer opnieuw.')
        file.close()

# 2;peter
# 3;johan
# 6;piet
# 7;amk

def kluis_teruggeven():
    while True:
        file = open('fa_kluizen.txt', 'r+')
        safes = file.readlines()
        safenumber = input('voer uw kluisnummer hier in: ')
        password = input('voer uw wachtwoord van uw kluis hier in: ')
        safenumbercode = safenumber + ';' + password
        for safe in safes:
            safe = safe.strip()
            if safenumbercode == safe:
                numbercode = True
                break
            else:
                numbercode = False
        if numbercode == True:
            if safe.strip("\n") != numbercode:
                safe.write(safe)
            print('Kluis is verwijderd')
            break
        else:
            print('De kluisnummer en/of wachtwoord is onjuist, probeer opnieuw.')
    file.close()

can someone please help me :(

In the function to delete the safe, the file is already open, so you can clear the file and write the new safe list without the selected (deleted) safe.

def kluis_teruggeven():  # delete safe
    while True:
        file = open('fa_kluizen.txt', 'r+')
        safes = file.readlines()
        safenumber = input('voer uw kluisnummer hier in: ')
        password = input('voer uw wachtwoord van uw kluis hier in: ')
        safenumbercode = safenumber + ';' + password
        newlines = ""  # new file contents
        numbercode = False
        for safe in safes:
            safe = safe.strip()
            if safenumbercode != safe:
                newlines += safe + '\n'  # keep this safe
            else:
                numbercode = True  # found entry to be deleted
        if numbercode == True:
            file.truncate(0)  # clear file
            file.seek(0)
            file.write(newlines)  # write new contents
            print('Kluis is verwijderd')
            break
        else:
            print('De kluisnummer en/of wachtwoord is onjuist, probeer opnieuw.')
    file.close()

@mike67

i had one question

in my second option if you create a safe i wrote \\n so it starts writing underneath it but if i open the file the first line is empty because of that the first option says there are 10 safes left instead of 11 after 1 safe is used

what can i do to fix that issue

def nieuwe_kluis():
    safenumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    file = open('fa_kluizen.txt', 'r')
    safes = file.readlines()
    for safe in safes:
        safe_split = safe.split(";")
        for safenumber in safe_split:
            if safenumber in safenumbers:
                safenumbers.remove(safenumber)
    if len(safenumbers) > 0:
        safe_number = random.choice(safenumbers)
        print(f'u heeft kluisnummer {safe_number} gekregen')
        password = input('voer een wachtwoord in voor uw kluis: ')
        appendsafe = open('fa_kluizen.txt', 'a')
        appendsafe.write(f'\n{safe_number};{password}')
        appendsafe.close()
        print(f'uw Kluis is {safe_number} toegewezen!')
    else:
        print('Alle kluizen zijn al gebruikt.')
    file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM