is file open?

Fredrik Lundh fredrik at pythonware.com
Thu Dec 18 04:29:07 EST 2003


Maxim Khesin wrote:

> I have a script that processes a file generated by another program. I
> need an unumbiguous way to know that the file has been written and
> closed by the other program, at least on Windoze. I am thinking of doing
>
> def CanOpen(fname):
> try:
> f = open(fname, 'a')
> f.close()
> return True
> except IOError:
> return False
>
> should this work OK?

why not try it out:

>>> f = open("foo", "w")
>>> g = open("foo", "a")
>>> # do you see an exception?

many Windows programs lock the file, but it's no requirement.

As usual, the only unambigous way to make sure that another program are
done writing to the file is to have the other program use a temporary name
and rename when done.  A reasonable workaround is to check the mtime,
and only read the file if the mtime is old enough.

    if time.time() - os.path.getmtime(filename) >= LIMIT:
        ...

</F>








More information about the Python-list mailing list