python文件.write(字节)有效,但文件缺少字节



我编写了一个bittorrent客户端并成功下载所有文件的所有片段。

在写入文件(mode='wr')之前和之后,我将filename、piece_index、写入的字节数和偏移量打印到写入字节的文件中。所有文件写入后,我关闭这些文件。

但是,当我看磁盘时,只写了第一部分。该片段完全写入文件0和文件1的起始字节。尽管打印语句显示所有剩余部分都已写入文件1,但文件1没有这些部分。file.sek、file.write中没有错误。以下是一些输出:

-- first piece --    
offset: 0 piece_index: 0
about to write file 0: offset 0 start 0 nbytes 291
Distributed by Mininova.txt
just wrote 291 bytes at offset 0
about to write file 1: offset 0 start 291 nbytes 1048285    
DF self-extracting archive.exe
just wrote 1048285 bytes at offset 0
-- next piece --
offset: 1048285 piece_index: 1
about to write file 1: offset 1048285 start 1048576 nbytes 1048576
DF self-extracting archive.exe
just wrote 1048576 bytes at offset 1048285
-- next piece --
offset: 2096861 piece_index: 2 file_index: 1
about to write file 1: offset 2096861 start 2097152 nbytes 1048576
DF self-extracting archive.exe
just wrote 1048576 bytes at offset 2096861

代码:

def _write(self, fd, offset, start, num_bytes, row):
    print(fd.name[-30:])
    fd.seek(offset)  
    fd.write(self.buffer[row][start:start+num_bytes].tobytes())
    fd.seek(0)
    print('just wrote {} bytes at offset {}n'.format(num_bytes, offset))

这应该做:

def _write(self, fd, offset, start, num_bytes, row):
    print(fd.name[-30:])
    fd.seek(offset)
    bytes_ = self.buffer[row][start:start+num_bytes].tobytes()
    fd.write(bytes_)
    fd.flush()
    fd.seek(0)
    print('just wrote {} bytes at offset {}n'.format(len(bytes_), offset))
  1. 计算实际写入的字节数:len(bytes_)
  2. 写入后刷新文件。您也可以在打开文件时设置buffering=0

最新更新