繁体   English   中英

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

[英]python file.write(bytes) works but file is missing bytes

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

在写入文件之前和之后( mode='wr' ),我打印出文件名,piece_index,写入的字节数以及写入字节的文件中的偏移量。 写入所有文件后,我关闭文件。

但是,当我查看磁盘时,只写了第一部分。 该段完全写入文件0和文件1的开始字节。即使打印语句显示所有剩余的段都已写入文件1,文件1却没有。 file.seek,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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM