# NumbersToFile.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2006-05-14 File created. # 2022-12-27 Converted to Python 3. # This program writes binary values to a file. # https://docs.python.org/3/library/struct.html # Module pickle may be worth studying when you need to store # complex data to a file. import struct file_to_write = open( "NumbersToFile_output.data", "wb" ) integer_to_file = 0x22 while integer_to_file < 0x77 : file_to_write.write( struct.pack( 'i', integer_to_file ) ) integer_to_file = integer_to_file + 0x11 file_to_write.write( struct.pack( 'h', 0x1234 ) ) # short value file_to_write.write( struct.pack( 'd', 1.2345 ) ) # double value file_to_write.write( struct.pack( 'b', True ) ) # byte, boolean file_to_write.write( struct.pack( 'b', False ) ) # byte, boolean file_to_write.write( struct.pack( '8s', str.encode( "aaAAbbBB" ) ) ) # string (8 characters) bytes_to_file = [ 0x4B, 0x61, 0x72, 0x69 ] file_to_write.write( struct.pack( '4b', bytes_to_file[ 0 ], bytes_to_file[ 1 ], bytes_to_file[ 2 ], bytes_to_file[ 3 ] ) ) # Let's write a large byte 0xC9 to the end of file. file_to_write.write( struct.pack( 'B', 0xC9 ) ) file_to_write.close()