2017-08-19 111 views
-1

在我眼中,第二個for循環應該被輸入,但它永遠不會。爲什麼是這樣?這就像文件是空的,但我可以向你保證它不是。for循環不迭代文件

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) 
+0

oh和iv'e在第二個循環之前和之後添加了打印語句,所以我知道它沒有進入。它只是通過循環並繼續執行程序。它也沒有錯誤。 – Aaron

+0

可能的重複:[https://stackoverflow.com/questions/10255273/iterating-on-a-file-using-python](https://stackoverflow.com/questions/10255273/iterating-on-a-file -using-python) – vealkind

+0

你可以發佈temp_copy.txt –

回答

0

問題是

count =+1 

它應該是

count +=1 

記住這一點:

+ = IS加法運算符= +表示變量等於陽性數SO計數= + 1表示計數等於正1,而計數+ = 1表示計數加1 1

這應該解決問題!

此外,第一個循環讀取整個文件,並且您需要告訴它從頭再次開始。

+0

好地方,但它不是問題。不過謝謝。 – Aaron

0

第二個循環不運行,因爲第一個循環讀取整個文件。換句話說,當第一個循環完成時,可迭代文件位於序列的末尾。如果您想遍歷文件兩次,則可以使用file.seek(0)重置位置。

+0

非常感謝你,你擊中了頭部。問題已解決。 – Aaron