Search code examples
pythontextreadfile

Line extracted from text not matching the content of the text array


I have this block of code:

    def removal(i):
    with open(r"D:\Largecodefile\Customer.txt", "r") as f:
        lines = f.readlines()
    h,j = i-2,i-1
    data1, data2 = lines[h],lines[j]
    print('data is ',data1,'and',data2)
    print('line is ',lines)
    with open(r"D:\Largecodefile\Customer.txt", "w") as f:
        for line in lines:
            if line.strip('\n') != data1 and data2:
                f.write(line)

I'm trying to make it rewrite the file and exclude the specific line that I choose. As of right now, my line output is:

line is  ['JSJSJSJSJS\n', '10-02-1975\n', 'HAHAHAHAHA\n', '26-11-2001\n', 'BOTBOITBOT\n', '13-09-2018\n', 'Phill\n', 'Gill']

and data1 and data 2 is:

data is  Phill\n and Gill

They seem matchup to the list from I what see, however, the system is not recognizing it, I think the problem is at the second last line of the code but I can't make it work. Is it that I went wrong somewhere? Thank you!

Edit: Hi, it's me again, I just want to add that I've tried using 1 data to excluded it too and see if it works, if line.strip('\n') != data1: but sadly the result is still the same, I tried removing \n either, not reccomended but I did it anyway, does not get affected too


Solution

  • Thats a syntax mistake. You are checking if line is not equal to data1, and if data2 is True:

    if line.strip('\n') != data1 and data2:
    

    solution (check if line also is not equal to data2):

    if line != data1 and line != data2: