os.path.getsize() on Windows

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Mar 19 08:03:12 EDT 2008


On Tue, 18 Mar 2008 13:58:33 -0700, Sean DiZazzo wrote:

> I'm seeing some behavior that is confusing me.  I often use a simple
> function to tell if a file is growing...ie being copied into a certain
> location.  (Can't process it until it's complete)

Surely though, under Windows, while something else is writing to the file 
you can't open it? So instead of this:


def wait_for_open(pathname):
    """Return file open for reading, or fail. 
    If the file is busy, will wait forever.
    """
    import time
    while isGrowing(path, 0.2):  # defined elsewhere by you
        time.sleep(1)  # wait a bit
    # now we HOPE we can read the file
    return open(path, 'r')  # this can fail in many, many ways



do this:


def wait_for_open(pathname):
    """Return file open for reading, or fail. 
    If the file is busy, will wait forever.
    """
    import time, errno
    while True:
        try:
            return open(path, 'r')
        except IOError, e:
            if e.errno == errno.EBUSY:
                time.sleep(1)
             else:
                raise


Note: I've made a guess that the error you get under Windows is 
errno.EBUSY. You'll need to check that for yourself. This whole approach 
assumes that Windows does the sensible thing of returning a unique error 
code when you try to open a file for reading that is already open for 
writing.


-- 
Steven



More information about the Python-list mailing list