我需要编译一个二进制文件,其中的片段以随机顺序到达(是的,它是一个 P2P 项目)
def write(filename, offset, data)
file.open(filename, "ab")
file.seek(offset)
file.write(data)
file.close()
假设我在文件的偏移量 1MB 处有一个 32KB 写入(f,o,d),然后在偏移量 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 解决了一些困扰我一段时间的字节序问题。
对于任何想知道的人,我正在进行的项目是分析直接从网络捕获的 BT 消息。