简体   繁体   中英

python file.write(bytes) works but file is missing bytes

I wrote a bittorrent client and successfully downloaded all pieces for all files.

Before and after I write the files ( mode='wr' ), I print out filename, piece_index, number of bytes written, and the offset into the file where the bytes are written. After all files are written, I close the files.

BUT, when I look on the disk, only the first piece is written. The piece completely writes file 0 and the beginning bytes of file 1. Even though the print statements show all remaining pieces are written to file 1, file 1 does not have them. No error in file.seek, file.write. Here is some output:

-- 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

The code:

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))

This should do:

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. Calculate the bytes you actually write: len(bytes_)
  2. Flush the file after writing. You could also set buffering=0 when opening the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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