user17038048
user17038048

Reputation:

How can I use seek() in a binary file?

I am creating a simple tool to edit some specific binary values, so I need to control the offset positions by using seek(), but instead of returning the hexadecimal value, it shows every value I type into the parentheses. I am using a function for this, and it is activated by a command as soon as I open a file in Tkinter.

Here's how I did it:

def openFile():
    itaFile = filedialog.askopenfilename(
        filetypes=[("ITA Files", ".ITA"), ("All Files", "*")])
    itaOpened = open(itaFile, "rb+")
    itaOpened.read()
    a = itaOpened.seek(6)
    print(a)
    itaOpened.close()

I need it to return me this value at offset 06: https://i.sstatic.net/ICFPa.png

How can I solve it? If I am not specific enough, please tell me so I'll be more detailed.

Upvotes: 2

Views: 3596

Answers (1)

tdelaney
tdelaney

Reputation: 77337

seek changes the file postion but doesn't read anything. It wouldn't know in general how much to read. After the seek you can read 1 byte. As a side note, don't open with more rights than you need - no need to create an unnecessary failure point in your code.

def openFile():
    itaFile = filedialog.askopenfilename(
        filetypes=[("ITA Files", ".ITA"), ("All Files", "*")])
    with open(itaFile, "rb") as itaOpened:
        a = itaOpened.seek(6)
        a = itaOpened.read(1)
    print(a)

Upvotes: 2

Related Questions