Python Forum
How Write Part of a Binary Array?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How Write Part of a Binary Array?
#1
Windows 7
Python 3.8.10

I wish to read a binary file, and then write it's data to a different file, skipping the first 16 bytes.
How do I do that?

Python pseudo code:

oldfile = open("oldfile.dat", mode="rb")	#Open old file for binary read
newfile = open("newfile.dat", mode="wb")	#Open new file for binary write

olddata = oldfile.read()					#Read the original file

#How do I write olddata, after the first 16 bytes, into newfile.dat?
# newfile.write( From olddata[16] ?? )
Reply
#2
If the file's size is not too big, you could use pathlib directly
from pathlib import Path
Path('newfile.dat').write_bytes(Path('oldfile.dat').read_bytes()[16:])
If it is a large file, you may want to process it by chunks. There is an interesting piece of code in the documentation of the iter() function. Here is how it applies here
from functools import partial
CHUNK = 8192  # choose your preferred value
with open('oldfile.dat', 'rb') as filein:
    filein.read(16)
    with open('newfile.dat', 'wb') as fileout:
        for block in iter(partial(filein.read, CHUNK), b''):
            fileout.write(block)
Pedroski55 likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I read and write a binary file in Python? blackears 6 6,706 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  How to write a part of powershell command as a variable? ilknurg 2 1,132 Jul-26-2022, 11:31 AM
Last Post: ilknurg
  Read/Write binary file deanhystad 3 3,207 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  hex file to binary or pcap to binary baran01 1 5,706 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  How do I write class objects to a file in binary mode? Exsul1 7 5,788 Sep-14-2019, 09:33 PM
Last Post: snippsat
  class random var write to array storzo 5 2,910 Aug-02-2019, 03:26 PM
Last Post: storzo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020