0

To my eyes the second for loop should be entered but it never does. Why is this? It's like the file is empty but I can assure you it's not.

def remove_none():

# remove contents of temp.txt
file = open('temp.txt', 'w')
file.truncate()
file.close()    

with open("temp.txt", "a") as temp:
    with open("temp_copy.txt") as temp_copy:

        num_of_lines = 0
        other_IPs = 0

        # count the number of lines in temp_copy.txt
        for _ in temp_copy:
            num_of_lines += 1
        other_IPs = num_of_lines-3
        print "\nThere are {} IP's excluding router and you.\n".format(other_IPs)

        count = 0
        os.system("cat temp_copy.txt")

        **# this is the second for loop**
        for line in temp_copy:
            count =+ 1
            print count
            if count == 1:
                # run this on the first line
                temp.write(line)

            elif count == num_of_lines:
                # run this on the last line 
                # remove the last line
                pass
            else:
                # run this on every other line
                line = line[4:]+"\n"
                temp.write(line)
Aaron
  • 11
  • 2
  • oh and iv'e added print statements just before and after the second for loop so I know that it's not entering. It just passes the loop and continues with the program. It also gives no errors. – Aaron Aug 19 '17 at 23:03
  • Possible duplicate of: [https://stackoverflow.com/questions/10255273/iterating-on-a-file-using-python](https://stackoverflow.com/questions/10255273/iterating-on-a-file-using-python) – vielkind Aug 19 '17 at 23:05
  • can you post the temp_copy.txt – Victor Li Aug 19 '17 at 23:12
  • This is a duplicate of the above link by Bear Brown. – Aaron Aug 19 '17 at 23:55

2 Answers2

0

The problem is

count =+1

it should be

count +=1

REMEMBER THIS:

+= IS THE ADDITION OPERATOR =+ MEANS THE VARIABLE IS EQUAL TO THE POSITIVE NUMBER SO count =+ 1 means count is equal to positive 1 while count +=1 means count plus 1

That should solve the problem!

Also, the first loop reads the whole file and you need to tell it to start from the beginning again.

Pang
  • 9,564
  • 146
  • 81
  • 122
Victor Li
  • 113
  • 7
0

The second loop doesn't run because the first loop reads the entire file. In other words, the file iterable is at the end of the sequence when the first loop completes. If you want to iterate over the file twice you can reset the location with file.seek(0).

D.Shawley
  • 58,213
  • 10
  • 98
  • 113