我使用os.path.getsize()
将文件大小输出到标签。文件路径存储在列表框中。该函数有效,但它以位为单位输出文件大小,因此我编写了以下内容以转换为更合适的单位,现在它只显示在TB中。无论条件是否为真,它都会执行所有if
语句。
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'
答案 0 :(得分:1)
您的代码中存在几个问题,
fileSizeStr
。您需要连接新值。 fileSize
是否大于或等于1024,而不是更小。 fileSize
应该是第一次计算的剩余部分,而不是结果。此外,从较大的一个检查将是更好的恕我直言。
#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