我需要编译一个二进制文件,其中的部分以随机顺序到达(是的,它是一个p2p项目)
def write(filename, offset, data)
file.open(filename, "ab")
file.seek(offset)
file.write(data)
file.close()
假设我有一个32kb的写操作(f,o,d),偏移量为1Mb,然后在偏移量为0时有一个32kb的写操作(f,o,d)。
最后得到一个长度为65kb的文件(即32kb-1Mb之间由0组成的间隙被截断/消失)
我知道这可能是一个非常愚蠢的问题,但我似乎无法从file.open(..)模式中找到答案。
感激地接受了建议。
***更新
我写p2p片段的方法最终如下(对于那些可能从中获得一些价值的人)
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"r+b")
if not self.piecemap[ipdst].has_key(pieceindex):
little = struct.pack('<'+'B'*len(bytes), *bytes)
# Seek to offset based on piece index
file.seek(pieceindex * self.piecesize)
file.write(little)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
file.close()
注意:我还使用struct.pack解决了一些endian问题,这让我困扰了一段时间。
对于任何想知道的人来说,我正在进行的项目是分析直接从网络上捕获的BT消息。