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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4388201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:32:12  来源:igfitidea点击:

How to seek and append to a binary file in python?

pythonfileseek

提问by Kennedy

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.

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

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 seekdoes not work. How do i resolve this? are there other ways of achieving this?

您可以看到seek不起作用。我如何解决这个问题?还有其他方法可以实现这一目标吗?

Thanks

谢谢

采纳答案by Marcelo Cantos

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

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

回答by Paul

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

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

回答by rob

r+b should work as you wish

r+b 应该如你所愿

回答by shantanu pathak

NOTE : Remember new bytes over write previous bytes

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

As per python 3 syntax

根据 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())

OUTPUT

输出

b'This   textample'

remember new bytes over write previous bytes

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