title: Python file handling within threads
body: <p>Hello I have a program that looks through a range of data and finds anomalies in that data. To make my program faster I incorporated the use of threads  (66 in total) now when my program finds the anomalies I would want it to write it to a file but however when i try to write to the file from within multiple threads it wont write.here is a segment of it</p>
  
  <p>Python:</p>
  
  <pre><code>import threading
  
  class myThread(threading.Thread):
  def __init__(self,lock,output):
      threading.Thread.__init__(self)
      self.lock = lock
      self.file = output
  def run(self):
      main(self.lock,self.file)
  
  def main(lock,file):
       lock.acquire()
       file.write("It wont write :(")
       lock.release
  
  if __name__ == "__main__":
        lock = threading.Lock()
        file = open("file.txt","wb")
        thread1 = myThread(lock,file)
        thread1.start()
  </code></pre>
  
  <p>here is my code on a much smaller scale
  my error message is that file is not open for writing</p>
  
  <p>EDIT:this code for some reason works but my full length code seems to not work so I am going to post it</p>
  
  <pre><code>def main(START_IP,END_IP,lock,File):
    # store found DNS servers
    foundDNS=[]
  
    # scan all the ip addresses in the range
    for i0 in range(START_IP[0], END_IP[0]+1):
        for i1 in range(START_IP[1], END_IP[1]+1):
            for i2 in range(START_IP[2], END_IP[2]+1):
                for i3 in range(START_IP[3], END_IP[3]+1):
                    # build ip addres
                    ipaddr=str(i0)+"."+str(i1)+"."+str(i2)+"."+str(i3)
  
                    print "Scanning "+ipaddr+"...",
                    # scan address
                    ret=ScanDNS(ipaddr, 10)
  
                    if ret==True:
                      foundDNS.append(ipaddr)
                      print "Found!"
                      lock.acquire()
                      File.write(ipaddr)
                      File.write("\n")
                      File.flush()
                      lock.release()
  
                  else:
                      print 
  </code></pre>
  
  <p>This uses my exact same MyThread class just with the required arguments for main to manipulate the data. If I run my code for about a minute as its scanning over DNS servers
  I should get maybe 20-30 DNS servers saved into a file but I generally get this:</p>
  
  <p>FILE.TXT</p>
  
  <pre><code>   2.2.1.2
     8.8.8.8
     31.40.40
     31.31.40.40
     31.31.41.41
  </code></pre>
  
  <p>I know for a fact (because I watched the scanning output) and that it hardly all of them. So why is some writing and some not?</p>