[英]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.
我使用该命令以 ascii 格式将字符串附加到二进制文件中。
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.字符串长度最多为 40 个字符,如果较短,将用零填充。 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.此时您可以使用 fb。 In doing this, it will automatically close itself after the
with
has finished.这样做时,它会在
with
完成后自动关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.