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

发布于 2024-10-06 14:55:42 字数 484 浏览 8 评论 0原文

我在将数据附加到二进制文件时遇到问题。当我 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

囍笑 2024-10-13 14:55:42

在某些系统上,'ab' 强制所有写入发生在文件末尾。您可能需要'r+b'

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

ˇ宁静的妩媚 2024-10-13 14:55:42

r+b 应该如你所愿

r+b should work as you wish

§普罗旺斯的薰衣草 2024-10-13 14:55:42

省略搜索命令。您已经打开了要附加“a”的文件。

Leave out the seek command. You already opened the file for append with 'a'.

苏辞 2024-10-13 14:55:42

注意:记住新字节覆盖写入以前的字节

根据python 3语法

with open('myfile.dat', 'wb') as file:
    b = bytearray(b'This is a sample')
    file.write(b)

with open('myfile.dat', 'rb+') as file:
    file.seek(5)
    b1 = bytearray(b'  text')
    #remember new bytes over write previous bytes
    file.write(b1)

with open('myfile.dat', 'rb') as file:
    print(file.read())

输出

b'This   textample'

记住新字节覆盖写入以前的字节

NOTE : Remember new bytes over write previous bytes

As per python 3 syntax

with open('myfile.dat', 'wb') as file:
    b = bytearray(b'This is a sample')
    file.write(b)

with open('myfile.dat', 'rb+') as file:
    file.seek(5)
    b1 = bytearray(b'  text')
    #remember new bytes over write previous bytes
    file.write(b1)

with open('myfile.dat', 'rb') as file:
    print(file.read())

OUTPUT

b'This   textample'

remember new bytes over write previous bytes

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文