Changeset 7079 for main/waeup.sirp/trunk


Ignore:
Timestamp:
11 Nov 2011, 10:02:10 (13 years ago)
Author:
uli
Message:

Add helper to determine size of files reliably and for all regular
kinds of file/file-like objects.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • main/waeup.sirp/trunk/src/waeup/sirp/utils/helpers.py

    r7078 r7079  
    429429        return u'%.2f MB' % (number / 1024**2,)
    430430    return u'%.2f GB' % (number / 1024**3,)
     431
     432def file_size(file_like_obj):
     433    """Determine file size in most effective manner.
     434
     435    Returns the number of bytes in a file. This function works for
     436    both, real files as well as file-like objects like cStringIO based
     437    'files'.
     438
     439    Example:
     440
     441      >>> from cStringIO import StringIO
     442      >>> file_size(StringIO('my file content'))
     443      15
     444
     445    Please note that this function expects the file-like object passed
     446    in to be at first reading position (it does no seek(0)) and that
     447    when finished the file pointer might be at end of file.
     448    """
     449    if hasattr(file_like_obj, 'fileno'):
     450        return os.fstat(file_like_obj.fileno())[6]
     451    file_like_obj.seek(0, 2) # seek to last position in file
     452    return file_like_obj.tell()
Note: See TracChangeset for help on using the changeset viewer.