简体   繁体   English

如何读取文件的最后一个字节?

[英]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.

相关问题 如何从 python 中的文件中读取给定数量的字节? - How can I read a given amount of bytes from a file in python? 如何从二进制文件中读取除最后 X 个字节之外的所有字节? - How do I read all but the last X bytes from a binary file? 如何将 a.xlsx 文件读取为传递存储在局部变量中的文件字节的 pandas DataFrame? - How can I read a .xlsx file as a pandas DataFrame passing the bytes of the file stored in a local variable? 如何读取文件的确切字节? - How to read the exact bytes of the file? 如果csv文件的最后一行在Python中只有1列,我怎么不读它呢? - How can I not read the last line of a csv file if it has simply 1 column in Python? 如何通过将最后一列分配为元组的第二个值来读取csv文件? - How can I read in from a csv file by assigning last column as the second value of a tuple? 如何将CSV文件的最后一行读入我可以操作的列表(python) - How to read last line of CSV file into a list that I can manipulate (python) 如何使用python从字节文件中提取文本 - How can I extract a text from a bytes file using python 如何让 open() 在二进制文件的开头跳过字节? - How can I get open() to skip bytes at the beginning of a binary file? Python - 如何打开文件并以字节为单位指定偏移量? - Python - How can I open a file and specify the offset in bytes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM