如何在python中查找并附加到二进制文件? [英] How to seek and append to a binary file in python?

查看:94
本文介绍了如何在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中查找并附加到二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆