1

I'm adding a string at the end of a binary file, the problem is that I don't know how to get that string back. I append the string, to the binary file, in ascii format using that command.

f=open("file", "ab")
f.write("Testing string".encode('ascii'))
f.close()

The string length will be max 40 characters, if it is shorter it will be padded with zeros. But I don't know how to get the string back from the binary file since it is at the end and how to rewrite the file without the string. Thank you in advance.

Berry26
  • 37
  • 1
  • 5
  • Does this answer your question? [How to read the last MB of a very large text file](https://stackoverflow.com/questions/19046369/how-to-read-the-last-mb-of-a-very-large-text-file) – metatoaster Mar 13 '20 at 11:48
  • 1
    You need some way of marking the boundary between the end of the original file and the beginning of the string you appended. If I gave you a string like `abcdefg` and asked you to get back the string I had appended to it (knowing only that it was at most 4 characters), how would you know if I had appended `defg`, `efg`, `fg`, or `g`? – chepner Mar 13 '20 at 11:48
  • @metatoaster That assumes you know where to seek *to*. – chepner Mar 13 '20 at 11:49
  • The string length will be max 40 characters, if it is shorter it will be padded with zeros – Berry26 Mar 13 '20 at 18:00

1 Answers1

0

Since you opened the file in append mode, you can't read from it like that. You will need to reopen in in read mode like so:

f = open("file", "rb")
fb = f.read()
f.close()

For future reference, an easier way to open files is like this:

with open("file", "rb") as f:
    fb = f.read()

At which point you can use fb. In doing this, it will automatically close itself after the with has finished.

damaredayo
  • 1,048
  • 6
  • 19