operating system - Trouble outputing file size to a label from a listbox in Python 3 -
i'm using os.path.getsize()
output size of file label. file path stored in listbox. function works, outputs file size in bits, wrote following convert more appropriate units, , displaying in tb. it's executing of if
statements, regardless if condition 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'
there couple problems in code,
- you re-assign
filesizestr
. need concatenate new values. - you need check if
filesize
greater or equal 1024, not smaller. - new
filesize
should remainder of first calculation, not result of it.
also, checking larger 1 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 filled , 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
Comments
Post a Comment