Mohamad Dabdoub
Mohamad Dabdoub

Reputation: 25

How to remove certain set of line numbers in a text file using Python?

I need to delete for instance the following line numbers for instance; line_numbers = [67,68,69] How is it possible to do so? Actually, I am using the following code but it is not working.

f_in = 'Tendons_+Diagonals_Analysis1.tb'
f_out = 'Sample.tb'
_fileOne = open(f_in,'r')
f = open(f_out,'w')
    
counter=0
    
for line in fileinput.input([f_in]):
    counter = counter+1    
    if counter != (i for i in [67,68,69]):
          f.write(line)
    f.close()

Upvotes: 0

Views: 74

Answers (1)

Captain Trojan
Captain Trojan

Reputation: 2921

Do this instead:

for line in _fileOne:
    counter = counter+1    
    if counter not in [67,68,69]:
        f.write(line)
     
f.close()

Calling if counter != (i for i in [67,68,69]) is asking if counter, an int, is a generator expression (i for i in [67,68,69]), which it is not.

Also, as you already know, you're looking to remove a set of lines, not a list of lines, so it is more efficient to test

if counter not in {67, 68, 69}:

as opposed to

if counter not in [67, 68, 69]:

or

if counter not in (67, 68, 69):

Upvotes: 1

Related Questions