is file open?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Maxim Khesin

    is file open?

    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?

    thanks,
    max

  • Fredrik Lundh

    #2
    Re: is file open?

    Maxim Khesin wrote:
    [color=blue]
    > 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?[/color]

    why not try it out:
    [color=blue][color=green][color=darkred]
    >>> f = open("foo", "w")
    >>> g = open("foo", "a")
    >>> # do you see an exception?[/color][/color][/color]

    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.getmtim e(filename) >= LIMIT:
    ...

    </F>




    Comment

    Working...