A
A
Alexander2020-05-14 14:01:11
Python
Alexander, 2020-05-14 14:01:11

Byte-by-byte reading from a certain segment of the file?

Good afternoon!
There is a file inside the traffic (packet header + packet), I can read the file from the beginning and decode it in the right way. The problem is that sometimes I do not need to read the entire file, but subtract a range of bytes, I have to read the file from the beginning to the cut point.

For example, there is a file with a size of 12345 bytes, I need to cut a segment from 1234 to 7890 bytes from it.
Here is my working code, the question is whether it is possible to set a slice?

begin_f = 1234
end_f = 7890
n = 0

with open(file, 'rb') as ifile:
  while True:
    one_byte = ifile.read(1)  # думал делать размер чанка == (begin_f - 1), но плохо для больших файлов.
    if n == begin_f:
      with open(output_file, 'wb') as ofile:
        data = one_byte + ifile.read(end_f - begin_f - 1)
        ofile.write(data)
        break
    n += 1


In general, the question is how to skip an unnecessary gap of bytes in order to read from the right moment? And is it possible to read the file from the end?

Thanks for the replies and interesting examples.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Taus, 2020-05-14
@shabelski89

Use seek ( io.IOBase.seek ).

begin_f = 1234
end_f = 7890

bytes_to_read = end_f - begin_f
with open(file, 'rb') as ifile, open(output_file, 'wb') as ofile:
    ifile.seek(begin_f)
    data = ifile.read(bytes_to_read)
    ofile.write(data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question