Home > database >  Why does python delete every line except the first one?
Why does python delete every line except the first one?

Time:10-08

I have a text file with some data in it, and i've written a code that is supposed to delete a specific line when te if statement is true. Why does python delete every line except the first one? And how do i fix it?

def give_back():
    number_input = input('What is ur number?')
    code_input = input('Enter the code corresponding to your number.')
    b = [f'{number_input};{code_input}']

    with open('fa_kluizen.txt', 'r') as f:
        x = f.readlines()
    with open('fa_kluizen.txt', 'w') as f:
        for line in x:
            if line.strip('\n').strip() != b:
                f.write(line)
                return True
            else:
                return False

CodePudding user response:

You have two basic issues. The first is the way you handle your loop:

def give_back():
    ...
    return True  # leaves the function `give_back`

Even though you have a for line in x between these two statements, it will only ever run the first loop because you use the keyword return. This leaves the function. If you expect more work to be done, you need to avoid doing this.

Secondly, you are using the read-write flags awkwardly. When you open a file with open('somefile.txt', 'w') it opens for writing, truncating (deleting the contents of) the file first. If you plan to write every line back, that is fine, but since your loop only occurs once, the first line will be all that is in the file when you're done.

You don't say what you want the actual end result to look like with a given input, so it's impossible to say what the correct way to fix this is, but I'd start by getting rid of your return statements and see whether that matches what you're looking for.

CodePudding user response:

You probably meant something like this:

def give_back():
    number_input = input('What is ur number?')
    code_input = input('Enter the code corresponding to your number.')
    b = [f'{number_input};{code_input}']

    with open('fa_kluizen.txt', 'r') as f:
        x = f.readlines()
    with open('fa_kluizen.txt', 'w') as f:
        for line in x:
            if line.strip('\n').strip() != b:
                f.write(line)

The problem is that if u return the function exits

  • Related