0

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

fborges22
  • 313
  • 3
  • 14

1 Answers1

2

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])
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I tried to do this and I am getting this error: disk.write(xab[i]) TypeError: '_io.TextIOWrapper' object is not subscriptable – fborges22 Mar 10 '20 at 17:39
  • 1
    You wrote that `xab` is a list. Obviously it isn't, you need to access it properly/. – Barmar Mar 10 '20 at 17:41
  • xab = open("stuff.raw", "r") it was read a file and the contents stored in the variable xab – fborges22 Mar 10 '20 at 17:44
  • Try `xab = open("stuff.raw", "r").readlines()` to get a list of lines from the file. – Barmar Mar 10 '20 at 17:45
  • 2
    A file object is not a list. You can loop over it because it's an iterator, but you can't index it. – Barmar Mar 10 '20 at 17:46
  • Don't forget that the elements of `xab` will end with newline, you might want to strip those off. – Barmar Mar 10 '20 at 17:49
  • datastream = xab.read() i used this and now i am trying to complete the loop. By using this implementation can I get rid of newline? – fborges22 Mar 10 '20 at 17:58
  • Apparently it worked when i changed the 'rb+' to 'r+' i am still testing the disk image to see if it worked. Let me check to see. – fborges22 Mar 10 '20 at 18:09
  • If you are reading binary data, then instead of trying to get a "list of lines", it's probably better to open the file in binary mode and get a single chunk of bytes: `open("stuff.raw", "rb").read()`. – Karl Knechtel Mar 10 '20 at 18:54
  • If you use `xab.read()` you'll read the entire file as a single string, not a list. You can use `xab[i].rstrip('\n')` to remove the newline. – Barmar Mar 10 '20 at 19:01