0

I have a text file named testfile.txt:

admin>cat testfile.txt 
cat
cat
dog
rat
pig
cat

I have written a python script to remove all cat word from the file:

admin$ cat test.py
f1=open("testfile.txt","r")

f=f1.readlines()
print(f)
print (type(f))
print(len(f))
for x in f:
    if x=="cat\n":
        f.remove(x)
        print(f)
print (f)
print(len(f))
f1.close()

Output of the script is as follows:

admin$ python test.py 
['cat\n', 'cat\n', 'dog\n', 'rat\n', 'pig\n', 'cat\n']
<type 'list'>
6
['cat\n', 'dog\n', 'rat\n', 'pig\n', 'cat\n']
['dog\n', 'rat\n', 'pig\n', 'cat\n']
['dog\n', 'rat\n', 'pig\n', 'cat\n']
4

Question is why there is one "cat" left. In second iteration of the for loop it should remove the second "cat" in file but it is not removing it?

There is some issue with two consecutive cat [line#1, line#2].

Python version: Python 2.7.10 (default, Jul 15 2017, 17:16:57

0 Answers0