简体   繁体   中英

How can I read the last bytes of a file?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM