title: Python - appending to same file from multiple threads
body: <p>I'm writing an app that appends lines to the same file from multiple threads.</p>
  
  <p>I have a problem in which some lines are appended without a new line.</p>
  
  <p>Any solution for this?</p>
  
  <pre><code>class PathThread(threading.Thread):
      def __init__(self, queue):
          threading.Thread.__init__(self)
          self.queue = queue
  
      def printfiles(self, p):
          for path, dirs, files in os.walk(p):
              for f in files:
                  print(f, file=output)
  
      def run(self):
          while True:
              path = self.queue.get()
              self.printfiles(path)
              self.queue.task_done()
  
  
  pathqueue = Queue.Queue()
  paths = getThisFromSomeWhere()
  
  output = codecs.open('file', 'a')
  
  # spawn threads
  for i in range(0, 5):
      t = PathThread(pathqueue)
      t.setDaemon(True)
      t.start()
  
  # add paths to queue
  for path in paths:
      pathqueue.put(path)
  
  # wait for queue to get empty
  pathqueue.join()
  </code></pre>