如何在python中查找并附加到二进制文件?

编程入门 行业动态 更新时间:2024-10-28 00:20:13
本文介绍了如何在python中查找并附加到二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在将数据附加到二进制文件时遇到问题.当我seek()到某个位置,然后在该位置write()然后读取整个文件时,我发现数据未写入我想要的位置.相反,我在所有其他数据/文本之后立即找到它.

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.

我的代码

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不起作用.我该如何解决?还有其他方法可以实现这一目标吗?

You can see that the seek does not work. How do i resolve this? are there other ways of achieving this?

谢谢

推荐答案

在某些系统上,'ab'强制所有写入都在文件末尾进行.您可能需要'r+b'.

On some systems, 'ab' forces all writes to happen at the end of the file. You probably want 'r+b'.

更多推荐

如何在python中查找并附加到二进制文件?

本文发布于:2023-11-03 07:56:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二进制文件   如何在   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!