首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python file.write(字节)工作,但文件缺少字节

python file.write(字节)工作,但文件缺少字节
EN

Stack Overflow用户
提问于 2015-12-04 18:01:26
回答 1查看 855关注 0票数 0

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

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

但是,当我查看磁盘时,只编写了第一部分。文章完全写入文件0和文件1的开头字节。即使打印语句显示所有剩余的部分都写入文件1,但文件1没有它们。在file.seek,file.write中没有错误。以下是一些输出:

代码语言:javascript
复制
-- 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

守则:

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-04 18:51:39

这应该可以做到:

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34094593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档