title: Python: Lock a file
body: <p>I have a Python app running on Linux. It is called every minute from cron. It checks a directory for files and if it finds one it processes it - this can take several minutes. I don't want the next cron job to pick up the file currently being processed so I lock it using the code below which calls portalocker. The problem is it doesn't seem to work. The next cron job manages to get a file handle returned for the file all ready being processed.</p>
  
  <pre><code>def open_and_lock(full_filename):
      file_handle = open(full_filename, 'r')
      try:
          portalocker.lock(file_handle, portalocker.LOCK_EX
                              | portalocker.LOCK_NB)
          return file_handle
      except IOError:
          sys.exit(-1)
  </code></pre>
  
  <p>Any ideas what I can do to lock the file so no other process can get it?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Thanks to @Winston Ewert I checked through the code and found the file handle was being closed way before the processing had finished. It seems to be working now except the second process blocks on portalocker.lock rather than throwing an exception.</p>