Hi,
I want to know how to read the binary file from 10th byte to 90th byte in a file size of 100 bytes and need to write the read data into new binary file.
please help me in doing this.

Dani AI

Generated

A few clarifications and a couple of safer alternatives to the quick answers already posted by and .

The usual off-by-one confusion comes from human (1-based) versus programmatic (0-based) numbering. For a 1-based inclusive range start..end, compute zero_based_start = start - 1 and length = end - start + 1. Python slicing is half-open ([start:stop]) so the equivalent slice is [zero_based_start:end]. That formula avoids guessing whether you should seek(9) vs seek(10) or read 80 vs 81 bytes.

For a robust, memory-efficient extraction use a memory map so the OS handles paging instead of loading the whole file into Python objects:

import os
import mmap

infile = "binfile.dat"
start = 10    # 1-based inclusive
end = 90      # 1-based inclusive

size = os.path.getsize(infile)
if end > size:
    raise ValueError("input too small")

with open(infile, "rb") as f:
    with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
        chunk = m[start - 1:end]   # zero-based slice gives inclusive start..end

with open("out.dat", "wb") as out:
    out.write(chunk)

Quick troubleshooting/checks: confirm the output length equals (end - start + 1) using os.path.getsize; inspect a few leading bytes with binascii.hexlify if the result looks wrong. On very large files or unusual platforms, prefer a small seek/read loop or use readinto with a preallocated bytearray. See the Python docs for memory-mapped files and file size checks: mmap module docs and os.path.getsize.

Recommended Answers

All 3 Replies

with open('binfile.dat', 'rb') as bf:
      bf.seek(10)
      open('out.dat', 'wb').write(bf.read(80))

Something like this. This is untested as I am not with computer now. Maybe you must seek(9) and/or read(81).

You should be able to read the 100 bytes, split and write. The following code uses 25 bytes and splits from 10 through 20 (11 bytes) for simplicity.

alpha = "abcdefghijklmnopqrstuvwxy"
print alpha
print alpha[9:20]

The first solution really worked for me.. thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.