Search code examples
pythonbytetruncate

Delete every 5th byte of a large file with Python


I tried this code to delete every 5th byte of a large file, but it doesn't work:

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

What is wrong?


Solution

  • Maybe this will help?

    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)