Check if a file is not open( not used by other process) in Python
<p>I my application, i have below requests:
1. There has one thread will regularly record some logs in file. The log file will be rollovered in certain interval. for keeping the log files small.
2. There has another thread also will regularly to process these log files. ex: Move the log files to other place, parse the log's content to generate some log reports.</p>

<p>But, there has a condition is the second thread can not process the log file that's using to record the log. in code side, the pseudocode similars like below:</p>

<pre><code>#code in second thread to process the log files
for logFile in os.listdir(logFolder):
     if not file_is_open(logFile) or file_is_use(logFile):
          ProcessLogFile(logFile) # move log file to other place, and generate log report....
</code></pre>

<p>So, how do i check is a file is already open or is used by other process?
I did some research in internet. And have some results:</p>

<pre><code>try:
   myfile = open(filename, "r+") # or "a+", whatever you need
except IOError:
    print "Could not open file! Please close Excel!"
</code></pre>

<p>I tried this code, but it doesn't work, no matter i use "r+" or "a+" flag</p>

<pre><code>try:
   os.remove(filename) # try to remove it directly
except OSError as e:
    if e.errno == errno.ENOENT: # file doesn't exist
        break
</code></pre>

<p>This code can work, but it can not reach my request, since i don't want to delete the file to check if it is open.</p>
