title: Python - Write for loop output to file
body: <p>I have a function that outputs a list of IPs.</p>
  
  <pre><code>def convertHostNamesToIps(hostnames):
      ip = server.system.search.hostname(sessionKey, hostnames )
      for ips in ip:
          print (ips.get('ip'))
  </code></pre>
  
  <p>The output usually looks like
  Below are the IPs for CSDP_LAB_STAGING</p>
  
  <pre><code>172.29.219.123
  172.29.225.5
  172.29.240.174
  172.29.225.46
  172.29.240.171
  172.29.240.175
  172.29.219.119
  172.29.219.117
  172.29.219.33
  172.29.219.35
  .
  .
  .
  172.29.219.40
  172.29.219.35
  172.29.219.40
  172.29.219.118
  172.29.219.121
  172.29.219.115
  172.29.225.51
  </code></pre>
  
  <p>Now I want to write this output to file.</p>
  
  <p>What I have done is </p>
  
  <pre><code>def convertHostNamesToIps(hostnames):
      ip = server.system.search.hostname(sessionKey, hostnames )
      sys.stdout=open("test.txt","w")
      for ips in ip:
          print (ips.get('ip'))
      sys.stdout.close()
  </code></pre>
  
  <p>But the above code only writes the very last IP to <code>test.txt</code>. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ? </p>
  
  <p>P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.</p>