2017-08-19 13 views
-1

私の目には、2番目のforループを入力する必要がありますが、それは決してありません。どうしてこれなの?それはファイルが空であるようですが、私はそれがあなたでないことを保証することができます。forループがファイルを反復しない

デフ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

2番目のforループの直前と直後にprintステートメントが追加されていますので、入力していないことがわかります。それは単にループを通過し、プログラムを続行します。また、エラーは発生しません。 – 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 

はTHISを覚えなければならない

count =+1 

ある:

+ =は、加算演算子IS = +は、変数を意味する正の数に等しいです。count = + 1は、カウントが正の1に等しいことを意味し、count + = 1は、カウントプラス1を意味します。

これで問題は解決します。

また、最初のループではファイル全体が読み込まれ、先頭から再び開始するように指示する必要があります。

+0

良い点ですが、それは問題ではありませんでした。しかし、ありがとう。 – Aaron

0

最初のループがファイル全体を読み取るため、2番目のループは実行されません。つまり、ファイルiterableは、最初のループが完了したときにシーケンスの最後にあります。ファイルを2回反復処理したい場合は、file.seek(0)で位置をリセットすることができます。

+0

ありがとう、あなたは頭の爪を打つ。問題は修正されています。 – Aaron

関連する問題