17

I am having problems appending data to a binary file. When i seek() to a location, then write() at that location and then read the whole file, i find that the data was not written at the location that i wanted. Instead, i find it right after every other data/text.

My code

file = open('myfile.dat', 'wb')
file.write('This is a sample')
file.close()

file = open('myfile.dat', 'ab')
file.seek(5)
file.write(' text')
file.close()

file = open('myfile.dat', 'rb')
print file.read()  # -> This is a sample text

You can see that the seek does not work. How do i resolve this? are there other ways of achieving this?

Thanks

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Kennedy
  • 2,146
  • 6
  • 31
  • 44

4 Answers4

37

On some systems, 'ab' forces all writes to happen at the end of the file. You probably want 'r+b'.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 8
    From the docs for the `seek` method: "If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op," – bgporter Dec 08 '10 at 14:13
  • @bgporter: Are you supporting or refuting something I said? I honestly can't tell. – Marcelo Cantos Dec 08 '10 at 14:16
  • 1
    Sorry -- supporting! Just adding the actual text from the docs, trying to clarify (but obviously failing..) – bgporter Dec 08 '10 at 14:27
  • 1
    The non-intuitive part thing is that the docs say `'r+'` opens the file for both reading and *updating* -- with the latter implying being able to write. – martineau Dec 08 '10 at 20:32
6

r+b should work as you wish

rob
  • 61
  • 1
3

Leave out the seek command. You already opened the file for append with 'a'.

Paul
  • 4,812
  • 3
  • 27
  • 38
-1

NOTE : Remember new bytes over write previous bytes

As per python 3 syntax

with open('myfile.dat', 'wb') as file:
    b = bytearray(b'This is a sample')
    file.write(b)

with open('myfile.dat', 'rb+') as file:
    file.seek(5)
    b1 = bytearray(b'  text')
    #remember new bytes over write previous bytes
    file.write(b1)

with open('myfile.dat', 'rb') as file:
    print(file.read())

OUTPUT

b'This   textample'

remember new bytes over write previous bytes

wjandrea
  • 28,235
  • 9
  • 60
  • 81
shantanu pathak
  • 2,018
  • 19
  • 26
  • so, how can we wb those two variables into a file and read them? – Glenio Mar 22 '20 at 03:52
  • Do you mean writing them on different lines? in that case, you can use file.seek(len(b)) the second time. OR best way is to write both variables one after the other when you open file in writing mode. Then close the file. And next time open file in reading mode and read all contents – shantanu pathak Mar 23 '20 at 06:32
  • it doesn't have to be on a different line, I have posted a question about this. https://stackoverflow.com/questions/60795901/python-transferring-two-byte-variables-with-a-binary-file. Thanks – Glenio Mar 24 '20 at 05:26