Dixie Kick Dixie Kick - 4 months ago 39
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?")

text_file.close()


or

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? ")

text_file.close()


minigolf.txt contains:

Sara;37;32;47;
Johan;44;29;34;
Kalle;33;34;34;
Oskar;23;47;45;

Answer

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
        users.add(line[:line.index(';')].lower())
        print(line[:line.index(';')].lower())

    # get result from user with exception handling
    result = None
    while not result:
        delete_player = raw_input('Which user do you want to delete? ')
        try:
            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:
        f.writelines(new_file)

if __name__ == '__main__':
    delete_result()

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