Dixie Kick Dixie Kick - 1 year ago 144
Python Question

Delete line in file

I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete.

This is what I tried so far, but I'm kinda stuck.

def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0
for line in text_file:
zork = zork + 1
print zork, line

delete_player = raw_input ("Who's result do you want to delete?")



def delete_result():
text_file = open('minigolf.txt', 'r')
for line in text_file:
if ';' in line:
line2 = line.split(";")
print line2
print "***"
delete = raw_input ("Who's result do you want to delete? ")


minigolf.txt contains:


Answer Source

This will solve your issue and give you a more robust way of handling user input:

def delete_result():
    with open('minigolf.txt', 'r') as f:
        text_file = f.readlines()

    # strip newlines from endings
    text_file = [t[:-1] if t[-1] == '\n' else t for t in text_file]

    users = set()
    for line_number, line in enumerate(text_file):
        print line_number + 1, line

    # get result from user with exception handling
    result = None
    while not result:
        delete_player = raw_input('Which user do you want to delete? ')
            result = str(delete_player).lower()
            assert result in users
        except ValueError:
            print('Sorry, I couldn\'t parse that user.')
        except AssertionError:
            print('Sorry, I couldn\'t find that user.')
            result = None

    # write new file
    new_file = [t + '\n' for t in text_file
                             if t[:t.index(';')].lower() != result]
    with open('minigolf.txt', 'w') as f:

if __name__ == '__main__':

EDIT: I saw that you wanted to wanted to delete by name, not line number, so changed it to resemble @danidee's method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download