Trouble outputing file size to a label from a listbox in Python 3

I'm using os.path.getsize() to output the size of a file to a label. The file path is stored in a listbox. The function works, but it outputs the file size in bits, so I wrote the following to convert to more appropriate units, and it is now displaying only in TB. It's executing all of the if statements, regardless if the condition is true.

activeFile = FilesList.get(ACTIVE)
fileSize = os.path.getsize(activeFile)
fileSizeStr = str(fileSize) + ' Bits'

if fileSize > 8:
    fileSize = fileSize / 8
    fileSizeStr = str(fileSize) + ' Bytes'

if fileSize < 1024:
    fileSize = fileSize / 1024
    fileSizeStr = str(fileSize) + ' KB'

if fileSize < 1024:
    fileSize = fileSize / 1024
    fileSizeStr = str(fileSize) + ' MB'

if fileSize < 1024:
    fileSize = fileSize / 1024
    fileSizeStr = str (fileSize) + ' GB'

if fileSize < 1024:
    fileSize = fileSize / 1024
    fileSizeStr = str(fileSize) + ' TB'

Answers


There are couple problems in your code,

  • You always re-assign fileSizeStr. You need to concatenate new values.
  • You need to check if fileSize greater than or equal to 1024, not smaller.
  • New fileSize should be remainder of the first calculation, not the result of it.

Also, checking from larger one would be better IMHO.

#constants
TB = 2**43
GB = 2**33
MB = 2**23
KB = 2**13
BYTES = 2**3

#some test value here
fileSize = 8

#empty string to be filled and shown later
fileSizeStr = ""

#calculations
if fileSize >= TB:
    fileTB = fileSize / TB
    fileSize = fileSize % TB
    fileSizeStr += str(fileTB) + 'TB '

if fileSize >= GB:
    fileGB = fileSize / GB
    fileSize = fileSize % GB
    fileSizeStr += str(fileGB) + 'GB '

if fileSize >= MB:
    fileMB = fileSize / MB
    fileSize = fileSize % MB
    fileSizeStr += str(fileMB) + 'MB '

if fileSize >= KB:
    fileKB = fileSize / KB
    fileSize = fileSize % KB
    fileSizeStr += str(fileKB) + 'KB '

if fileSize >= BYTES:
    fileB = fileSize / BYTES
    fileSize = fileSize % BYTES
    fileSizeStr += str(fileB) + 'Byte(s) '

fileSizeStr += str(fileSize) + 'Bit(s)'

print fileSizeStr

Need Your Help

Debugging iframes with Chrome developer tools

debugging iframe google-chrome

I'd like to use the Chrome developer console to look at variables and DOM elements in my app, but the app exists inside an iframe (since it's an OpenSocial app).

Django get url path without using "request.path"

python django url path http-status-code-404

I am creating a 404.html page in django which will be called when i raise "Http404"