简体   繁体   English

用 Python 覆盖大文件的一部分

[英]Overwrite part of a large file in Python

I am writing a bit torrent client and allocate space on hard drive for each file I have to download.我正在编写一个洪流客户端,并为我必须下载的每个文件在硬盘上分配空间。

File can be huge and I want to overwrite some piece of it without deleting all content.文件可能很大,我想覆盖其中的一部分而不删除所有内容。

I read some other answers, but they suggest creating a temporary space and then copying changes back.我阅读了其他一些答案,但他们建议创建一个临时空间,然后将更改复制回来。 That would be too heavy process.那将是太沉重的过程。

I am sure there must be some utility.我相信一定有一些效用。

Since you are talking about a download file, you should consider the storage of downloaded data in a temporary file(chunks).由于您在谈论下载文件,因此您应该考虑将下载的数据存储在临时文件(块)中。 Refer : streaming & text-file参考: 流媒体文本文件

If I read you question (without python), I would say you could use OS specific commands to overwrite parts of a file.如果我读到你的问题(没有 python),我会说你可以使用操作系统特定的命令来覆盖文件的一部分。

For example in Linux, use sed or awk .例如在 Linux 中,使用sedawk Refer : Inserting-a-line-in-a-file-at-a-specific-location请参阅: 在特定位置插入文件中的行

I found a solution, using OS (Linux) specific system call:我找到了一个解决方案,使用操作系统(Linux)特定的系统调用:

fd = os.open(path, os.O_WRONLY)
os.lseek(fd, offset, os.SEEK_SET)
os.write(fd, piece)
os.close(fd)

This did overwrite file without nullifying it.这确实覆盖了文件而不会使它无效。 But when had:但是当有:

with open(path, 'wb') as file:
    file.seek(offset)
    file.write(piece)

It was deleting all other content.它正在删除所有其他内容。

Program is not portable this way but I don't need it to be.程序不能以这种方式移植,但我不需要它。

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

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