Search code examples
pythonpython-2.7fat32

Format a USB drive to FAT32 using Python


I'm trying to create a bootable USB drive and need to format the USB into FAT32 so that I can extract all the files into it.

Is it possible to format a USB drive using pure python? Can I format it into FAT32 without the use of external commands?

I know that in bash I can do this: sudo dd if=/dev/zero of=/dev/sdb bs=4k && sync to format the USB drive, how can I do similar using just python?


Solution

  • The following is a close approximation to the dd command you gave in the question. I'm not sure if there's a way to force a sync after completion.

    import io
    block = b'\0' * 4096
    with io.FileIO('/dev/sdb', 'w') as f:
        while f.write(block):
            pass