title: python write to file in real time
body: <p>I have this piece of python code, that loops thru a list of urls in a text file(urls.txt) then follows redirects of all urls and if the url contains a specific string, it writes it to a file called redirects.txt</p>
  
  <pre><code>import urllib.request
  import ssl
  redf = open('redirect.txt', 'w')
  with open('urls.txt') as f:
     for row in f:
      #try:
  
        context = ssl._create_unverified_context()
        finalurl = ''
        try:
          res      = urllib.request.urlopen(row, context=context, timeout=10)
          finalurl = res.geturl().strip()
        except:
            #remove from list
            print("error:"+finalurl)
  
        # filedata = file.read()
        if finalurl.strip():
          if "/admin/" in finalurl:
              redf.write(finalurl+"\n");
  </code></pre>
  
  <p>The problem is that I have to wait for the entire URS to be processed before the redirect.txt file is created.</p>
  
  <p>How can I write in real time?</p>