如何在 python 中查找并附加到二进制文件?
我在将数据附加到二进制文件时遇到问题。当我 seek()
到某个位置,然后在该位置 write()
,然后读取整个文件时,我发现数据没有写入我指定的位置通缉。相反,我在所有其他数据/文本之后找到它。
我的代码
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
您可以看到 seek
不起作用。我该如何解决这个问题?还有其他方法可以实现这一目标吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在某些系统上,
'ab'
强制所有写入发生在文件末尾。您可能需要'r+b'
。On some systems,
'ab'
forces all writes to happen at the end of the file. You probably want'r+b'
.r+b 应该如你所愿
r+b should work as you wish
省略搜索命令。您已经打开了要附加“a”的文件。
Leave out the seek command. You already opened the file for append with 'a'.
注意:记住新字节覆盖写入以前的字节
根据python 3语法
输出
记住新字节覆盖写入以前的字节
NOTE : Remember new bytes over write previous bytes
As per python 3 syntax
OUTPUT
remember new bytes over write previous bytes