Write raw disk bytes in Python

749 Views Asked by At

I am looking for a way to write raw bytes into a disk image using Python. For example, I have an list containing several characters and I need to write all those characters in different parts of my disk.

In my Python script I need to do something like this: My list xab contains all those characters that I need to write in my this and the SelectedSectors list contains the sectors that will be written with each xab characters.

disk = open("mydisk.img",'ab')
for i in SelectedSectors:
    disk.seek(SelectedSectors[i])
    disk.write(xab[i])
disk.close()

I am not sure in how to deal with individual bytes in my disk image using Python. How should I solve this problem?

Best regards,

F.Borges

1

There are 1 best solutions below

10
On BEST ANSWER

Append mode automatically performs all writes at the end. Open the file in rb+ mode. r prevents truncating the file when it's opened, and + allows writing in addition to reading.

Also, for i in SelectedSectors sets i to the elements of the list, not the indexes; you don't need to index the list inside the loop.

with open("mydisk.img",'rb+') as disk:
    for i in SelectedSectors:
        disk.seek(i)
        disk.write(xab[i])