[Python] Parse human-readable filesizes into bytes

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    example_strings = ["10.43 KB", "11 GB", "343.1 MB"]


    I want to convert all this strings into bytes. So far I came up with this:

    def parseSize(size):
    if size.endswith(" B"):
    size = int(size.rstrip(" B"))
    elif size.endswith(" KB"):
    size = float(size.rstrip(" KB")) * 1000
    elif size.endswith(" MB"):
    size = float(size.rstrip(" MB")) * 1000000
    elif size.endswith(" GB"):
    size = float(size.rstrip(" GB")) * 10000000000
    elif size.endswith(" TB"):
    size = float(size.rstrip(" TB")) * 10000000000000
    return int(size)


    But I don't like it and also I don't think it works. I could find only modules that do the opposite thing.

    Continue reading...

Compartilhe esta Página