使用 Python 删除大文件的每 5 个字节

Delete every 5th byte of a large file with Python

我试过这段代码删除一个大文件的每 5 个字节,但它不起作用:

from io import BytesIO

f = open("data.bin", 'rb')
chunk = f.read(5)
while chunk:
    # Truncate the chunk.
    BytesIO(chunk).truncate(5 - 1)
    chunk = f.read(5)
f.close()

怎么了?

也许这会有帮助?

from pathlib import Path

source_path = Path("source_file.txt")
destination_path = Path("temporary_file.txt")
with source_path.open("rb") as source:
    with destination_path.open("wb") as destination:
        bytes = source.read(5)
        while len(bytes) > 0:
            # print(f"{bytes} => {bytes[:4]}")
            destination.write(bytes[:4])
            bytes = source.read(5)

destination_path.rename(source_path)