5

我想复制一个没有前 256 个字节的文件。

在 python 中有一个很好的方法吗?

我猜简单的方法是用计数器读取字节字节,然后只有在达到 256 时才开始复制。

我希望有更优雅的方式。

谢谢。

4

3 回答 3

8
with open('input', 'rb') as in_file:
    with open('output', 'wb') as out_file:
        out_file.write(in_file.read()[256:])
于 2013-08-27T13:12:46.703 回答
6

用于seek跳过前 256 个字节,然后分块复制文件以避免将整个输入文件读入内存。另外,请确保使用with以使文件正确关闭:

with open('input.dat', 'rb') as inFile:
    inFile.seek(256)
    with open('output.dat', 'wb') as outFile:
        for chunk in iter(lambda: inFile.read(16384), ''):
            outFile.write(chunk)
于 2013-08-27T13:23:09.423 回答
4
f = open('filename.ext', 'rb')
f.seek(255) # skip the first 255 bytes
rest = f.read() # read rest
于 2013-08-27T12:50:40.263 回答