Bytes-to-human / human-to-bytes converter. Based on: http://goo.gl/kTQMs Working with Python 2.x and 3.x. Author: Giampaolo Rodola' License: MIT
(n, format="%(value).1f %(symbol)s", symbols="customary")
| 118 | |
| 119 | |
| 120 | def bytes2human(n, format="%(value).1f %(symbol)s", symbols="customary"): |
| 121 | """ |
| 122 | Bytes-to-human / human-to-bytes converter. |
| 123 | Based on: http://goo.gl/kTQMs |
| 124 | Working with Python 2.x and 3.x. |
| 125 | |
| 126 | Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com> |
| 127 | License: MIT |
| 128 | """ |
| 129 | |
| 130 | """ |
| 131 | Convert n bytes into a human readable string based on format. |
| 132 | symbols can be either "customary", "customary_ext", "iec" or "iec_ext", |
| 133 | see: http://goo.gl/kTQMs |
| 134 | |
| 135 | >>> bytes2human(0) |
| 136 | '0.0 B' |
| 137 | >>> bytes2human(0.9) |
| 138 | '0.0 B' |
| 139 | >>> bytes2human(1) |
| 140 | '1.0 B' |
| 141 | >>> bytes2human(1.9) |
| 142 | '1.0 B' |
| 143 | >>> bytes2human(1024) |
| 144 | '1.0 K' |
| 145 | >>> bytes2human(1048576) |
| 146 | '1.0 M' |
| 147 | >>> bytes2human(1099511627776127398123789121) |
| 148 | '909.5 Y' |
| 149 | |
| 150 | >>> bytes2human(9856, symbols="customary") |
| 151 | '9.6 K' |
| 152 | >>> bytes2human(9856, symbols="customary_ext") |
| 153 | '9.6 kilo' |
| 154 | >>> bytes2human(9856, symbols="iec") |
| 155 | '9.6 Ki' |
| 156 | >>> bytes2human(9856, symbols="iec_ext") |
| 157 | '9.6 kibi' |
| 158 | |
| 159 | >>> bytes2human(10000, "%(value).1f %(symbol)s/sec") |
| 160 | '9.8 K/sec' |
| 161 | |
| 162 | >>> # precision can be adjusted by playing with %f operator |
| 163 | >>> bytes2human(10000, format="%(value).5f %(symbol)s") |
| 164 | '9.76562 K' |
| 165 | """ |
| 166 | n = int(n) |
| 167 | if n < 0: |
| 168 | raise ValueError("n < 0") |
| 169 | symbols = SYMBOLS[symbols] |
| 170 | prefix = {} |
| 171 | for i, s in enumerate(symbols[1:]): |
| 172 | prefix[s] = 1 << (i + 1) * 10 |
| 173 | for symbol in reversed(symbols[1:]): |
| 174 | if n >= prefix[symbol]: |
| 175 | value = float(n) / prefix[symbol] |
| 176 | return format % locals() |
| 177 | return format % dict(symbol=symbols[0], value=n) |
no outgoing calls
no test coverage detected