integer 10진수 11과 3을  이진파일에 쓰기

import struct 

file = open('파일명.bin','wb+')

tempbin = struct.pack('ii',11,3)##i는 int를 뜻하며 4바이트다. 다양한 포맷이 올수있다 i,h,c,I,B

file.write(tempbin)

file.close()

 생성된 이진파일

 0b 00 00 00 03 00 00 00

 

※ struct : python 자료형들을 'bytes' 형으로 변환 시켜준다.

struct.pack(fmt, v1, v2, ...)

Return a bytes object containing the values v1, v2, ... packed according to the format string fmt. The arguments must match the values required by the format exactly.

struct.pack_into(fmt, buffer, offset, v1, v2, ...)

Pack the values v1, v2, ... according to the format string fmt and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.

struct.unpack(fmt, buffer)

Unpack from the buffer buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer must contain exactly the amount of data required by the format (len(bytes) must equal calcsize(fmt)).

struct.unpack_from(fmt, buffer, offset=0)

Unpack from buffer starting at position offset, according to the format string fmt. The result is a tuple even if it contains exactly one item. buffer must contain at least the amount of data required by the format (len(buffer[offset:]) must be at least calcsize(fmt)).

struct.calcsize(fmt)

Return the size of the struct (and hence of the bytes object produced by pack(fmt, ...)) corresponding to the format string fmt.

Format(fmt) C Type Python type Standard size Notes
x pad byte no value    
c char bytes of length 1 1  
b signed char integer 1 (1),(3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long long integer 8 (2), (3)
n ssize_t integer   (4)
N size_t integer   (4)
f float float 4 (5)
d double float 8 (5)
s char[] bytes    
p char[] bytes    
P void * integer   (6)

python 3.3 struct documentation : http://docs.python.org/py3k/library/struct.html

 

이진 파일 변형없이 읽어오기 

 try:
    file = open('파일명.bin','rb')
    while True:
        temp = file.read(1)
        if temp == '' : break
        ## temp type 'bytes'
        print("%02x "% ord(temp),end='')
        ##ex) ord('a') -> 97 chr(97) -> 'a'
    file.close()
except IOError:
    print("IO error")

 결과

 <원본 이진파일>

d4 c3 00 02 18 f3 27

< print결과화면>

d4 c3 00 02 18 f3 27

 

 

현재시간 timestamp 형 이진파일에 저장 

import time

import struct

 

file = open('파일명.bin','wb+')

temptimestamp=time.time()##현재시간 timestamp 형으로 저장

tempchar = struct.pack('I',int(temptimestamp))

file.write(tempchar)

file.close()

결과

 10/06/2012 14:18:47

<이진 파일 내용>

C7 3D 70 50

 

 

+ Recent posts